设为首页 加入收藏

TOP

设计模式 - 单例模式之多线程调试与破坏单例(五)
2019-10-10 11:17:42 】 浏览:496
Tags:设计模式 单例 模式 线程 调试 破坏
JDK 源码,进入ConstructornewInstance()方法中:

    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;
        }
    }

原来,在源码中对枚举类型进行了强制性的判断(16384代表枚举类型),如果是枚举类型,直接抛异常。到此为止也就说明了为什么《Effective Java》推荐使用枚举来实现单例的原因: JDK 枚举的语法特殊性,以及反射也为枚举保驾护航,让枚举式单例成为一种比较优雅的实现。


本文中所涉及的源码可在 github 上找到,相关的测试代码在 test 包下:https://github.com/eamonzzz/java-advanced

首页 上一页 2 3 4 5 下一页 尾页 5/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇设计模式-行为型-访问者模式 下一篇通俗易懂设计模式解析——迭代器..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目