Enum.valueOf() cannot be hidden by another static method valueOf of a concrete Enum type, but since I am creating my objects with reflection from text files I need a generic way to invoke valueOf.
Currently my Enum has a static class fromString():
public enum Fruits {
APPLE, ORANGE, ...;
public static Fruit fromString(String fruit) {
...
}
}
But how could I interface such a method that when I am dealing with an enum field type I invoke the appropriate method? The only thing I can think of is:
- using a marker interface
- implement this static method for every enum
- invoke the static method via reflection
Is there another alternative which enforces this restriction?
If I understand correctly, you’ll have a number of distinct enums that you want to integrate through the unique
fromStringmethod. What I have done is to make a separate class that accumulates all enum members into a singlestatic final Mapand thefromStringmethod is 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 irrespective of the exact enum in question.