美文网首页
枚举实现单例避免被反射破坏的原因

枚举实现单例避免被反射破坏的原因

作者: YAOPRINCESS | 来源:发表于2020-09-22 11:52 被阅读0次

主要是因为Construct类中的newInstance方法的一个判断条件
if ((this.clazz.getModifiers() & 16384) != 0) {
throw new IllegalArgumentException("Cannot reflectively create enum objects");
}
如果是枚举类型,就会抛出异常,因此只有枚举才能避免被反射破坏
反射在通过newInstance创建对象时,会检查该类是否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;
        }
    }

单例模式详解
https://www.cnblogs.com/chiclee/p/9097772.html

相关文章

网友评论

      本文标题:枚举实现单例避免被反射破坏的原因

      本文链接:https://www.haomeiwen.com/subject/zthwyktx.html