How to enter parameters into an enumeration constructor using Spring?

I have an enumeration like this:

public enum SomeEnum { ONE (new MyClass()), TWO (new MyClass()); private final MyClass instance; private SomeEnum(MyClass instance) { this.instance = instance; } } 

How to pass an instance of MyClass to an enumeration constructor from a Spring context? Is it possible?

I need this because I pass some parameters from the config file (.properties) to the MyClass instance when I create it. Now I am doing this in an xml file with beans, maybe there is another way?

+4
source share
2 answers

You cannot do this.

In this official Java tutorial on Enum types, he points out

Note. The constructor for the enumeration type must be private to the package or private access. It automatically creates constants that are defined at the beginning of the enumeration body. You cannot call an enumeration create yourself.

Since Enum is assumed to be a constant set of constants, it makes no sense to create new ones, so the constructors are inaccessible even when reflected.

+5
source

Even when we speak in the context of Spring, I think this is also impossible.

You cannot create instances because they are static. Therefore, I think Spring IoC also cannot create enumerations.

check out Spring IoC .

+2
source

Source: https://habr.com/ru/post/1496178/


All Articles