首页 > 解决方案 > Why doesn't java.lang.Enum::valueOf check for the null name first?

问题描述

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 and 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?

标签: javaenums

解决方案


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.


推荐阅读