主要是因?yàn)镃onstruct類中的newInstance方法的一個(gè)判斷條件
if ((this.clazz.getModifiers() & 16384) != 0) {
throw new IllegalArgumentException("Cannot reflectively create enum objects");
}
如果是枚舉類型,就會(huì)拋出異常,因此只有枚舉才能避免被反射破壞
反射在通過(guò)newInstance創(chuàng)建對(duì)象時(shí),會(huì)檢查該類是否ENUM修飾,如果是則拋出異常,反射失敗
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (!this.override) {
Class<?> caller = Reflection.getCallerClass();
this.checkAccess(caller, this.clazz, this.clazz, this.modifiers);
}
if ((this.clazz.getModifiers() & 16384) != 0) {
throw new IllegalArgumentException("Cannot reflectively create enum objects");
} else {
ConstructorAccessor ca = this.constructorAccessor;
if (ca == null) {
ca = this.acquireConstructorAccessor();
}
T inst = ca.newInstance(initargs);
return inst;
}
}