enum has valueOf(string)
method to get enum constant and the same type of method present in java.lang.Enum
class having name valueOf(enumClassName, string)
I found both are giving same output. Then what are other differences. If no difference then why JSL added Enum.valueOf()
?
enum Season {
WINTER,SUMMER
}
class Test {
public static void main(String[] args) {
String season = "WINTER";
//switch (Season.valueOf(colObject)) // following line achieves same thing
switch (Enum.valueOf(Season.class, season)) // any other difference between both approach
{
case WINTER: {
System.out.println("Got it in switch case= VENDOR");
break;
}
default:
System.out.println("Fell thru.");
break;
}
}
}
The reason the Enum.valueof()
method is included is that it works with any enum
. By contrast, the enum
valueof
method for a specific method only works for that specific enum
... since enum
classes cannot be used polymorphically.
Obviously the Enum.valueOf(...)
method is only really useful if you are implementing code that needs to work for multiple enum
types ... and generics don't cut it.
Enum.valueOf(Class<T>, String)
is used to implement the valueOf(String)
method generated into each specific enum class.
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