Reputation: 4949
Enum has a valueOf method:
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
So, when i have the enum:
public enum Basket {
APPLES, ORANGES, FLOWERS
}
the code
Basket b = Basket.valueOf(Basket.class, "APPLES");
brings me the same object as does
Basket b2 = Basket.APPLES;
i.e., b.equals(b2) is true out of the two lines above.
What i'm wondering is-- what is
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
good for.
There may be a use of it in the reflect API-- one that i can't put together right now. outside of that, does this method has a specific use? what would be missing, if the class Enum didn't have this method?
Same for the valueOf-with-single parameter-- defined implicitly in Enum:
Basket.valueOf("APPLES");
is doing the same thing as
Basket.valueOf(Basket.class, "APPLES");
What's the use?
Upvotes: 2
Views: 1324
Reputation: 5258
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
is used when you don't know exact Enum type. This is the case if you are writing a generic code. One example is deserializing json to java object. You can get the 'enumType' of a field though reflection and invoke,
Enum.valueOf(enumClass,fieldValue)
If you want to see real usage, check,
java.io.ObjectInputStream#readEnum
Upvotes: 3