目录
使用场景
原因
valueOf源码
enumConstantDirectory源码
使用valueOf()出现异常
public enum CertificateType {
ID_CARD(1, "身份证"),
PASSPORT(2, "护照"),
OTHERS(3, "其他"),
ORGANIZATION(4, "组织机构代码"),
BUSINESS_LICENSE(5, "营业证号"),
;
}
//发生错误的代码
CertificateType type = CertificateType.valueOf("身份证");
valueOf方法的入参类型为枚举对象名
public abstract class Enum>
implements Comparable, Serializable {
public static > T valueOf(Class 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);
}
}
valueOf核心为enumConstantDirectory(),获取结果见下图
valueOf获取的结果为
public final class Class implements java.io.Serializable,
GenericDeclaration,
Type,
AnnotatedElement {
Map enumConstantDirectory() {
if (enumConstantDirectory == null) {
T[] universe = getEnumConstantsShared();
if (universe == null)
throw new IllegalArgumentException(
getName() + " is not an enum type");
Map m = new HashMap<>(2 * universe.length);
for (T constant : universe)
m.put(((Enum>)constant).name(), constant);
enumConstantDirectory = m;
}
return enumConstantDirectory;
}
private volatile transient Map enumConstantDirectory = null;
}
拿到当前枚举类的各个对象组装结果如下: