Static Method Interface for Enum

Enum.valueOf() cannot be hidden by another static valueOf specific Enum type, but since I create my objects with reflection from text files, I need a general way to call valueOf .

Currently, my Enum has a static fromString() class:

 public enum Fruits { APPLE, ORANGE, ...; public static Fruit fromString(String fruit) { ... } } 

But how can I associate such a method when, when I deal with the enum field type, I call the appropriate method? The only thing I can think of:

  • using marker interface
  • implement this static method for each enumeration
  • invoke a static method using reflection

Is there any other alternative that limits this restriction?

+6
source share
2 answers

If I understand correctly, you will have several different enumerations that you want to integrate using the unique fromString method. I did to create a separate class that accumulates all enumeration elements into one static final Map , and the fromString method fromString implemented in terms of it.

All enums implement a common interface in my case, because I have a number of custom methods that I need to call regardless of the exact enumeration in question.

+2
source

Of course it is built-in: use Enum#valueOf(Class<T> enumType, String name) .

-2
source

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


All Articles