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:
Is there another alternative which enforces this restriction?
The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version.
static enum direction {UP,DOWN,RIGHT,LEFT}; This declares an enumerated type with the tag name directions , and also defines a number of enumeration constants and their values. The static storage-class is meaningless here, because you are not defining (allocating storage) for an object.
If I understand correctly, you'll have a number of distinct enums that you want to integrate through the unique fromString
method. What I have done is to make a separate class that accumulates all enum members into a single static final Map
and the fromString
method 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With