I have checked the source code for java.lang.Enum
and the method T valueOf(Class<T> enumType, String name)
beginning on line 232 (the implementation in both java-8 and java-11 seems equal; here is the source for Java 8).
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) {
T result = enumType.enumConstantDirectory().get(name);
if (result != null)
return result;
if (name == null)
throw new NullPointerException("Name is null");
throw new IllegalArgumentException(
"No enum constant " + enumType.getCanonicalName() + "." + name);
}
What is the reason the null check for name
happens after finding the enumeration by name in the Map
get using enumConstantDirectory()
? As far as I know, one cannot define a null
enum; therefore the following call makes no sense:
MyEnum myEnum = Enum.valueOf(MyEnum.class, null); // The NPE should be thrown
Although the HashMap
implementation allows null
as a key, I would expect the implementation would check for null
before iterating the Map
. What is the reason for this implementation and is there a case where searching for the null
key before comparing name == null
makes sense?
An ENUM can also contain NULL and empty values. If the ENUM column is declared to permit NULL values, NULL becomes a valid value, as well as the default value (see below).
If you want to represent null with an enum, then you'll have to explicit this by using a null object pattern manually with a NONE value and a custom implementation for prettyPrint() based on NONE value.
The Enum . IsDefined method should be used to determine whether a valid enumeration value has been passed to any method that accepts an enumeration value as a parameter. In particular, this Enum. IsDefined should always be used whenever the method is visible to external objects.
99.999+% of calls to that method will be valid enum names. Passing a null name is always a blunder and is not the case that you want to optimize for. So moving the null check three lines down means that the check will be skipped in the common case that the enum name is valid. It doesn't change the result; it's just a tiny optimization.
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