接上回的单例模式线程是否安全?
https://blog.csdn.net/weixin_45262118/article/details/108519818
我们先来谈谈枚举
枚举是JDK1.5推出的新特性,本身也是一个class类
我们先创建一个枚举
public enum EnumTest {
INSTANCE; //写一个就为单例public EnumTest getInstance() {
return INSTANCE;
}
}
枚举是线程安全的吗?直接上代码测试!
class SingleTest {
public static void main(String[] args) {
EnumTest instance1 = EnumTest.INSTANCE;
EnumTest instance2 = EnumTest.INSTANCE;System.out.println(instance1);
System.out.println(instance2);
}
}
通过反射的 newInstance 方法的源码得知 枚举无法通过反射创建对象
枚举无法用反射创建对象 我们测试一下
我们尝试通过反射枚举的无参构造创建来创建对象
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
EnumTest instance1 = EnumTest.INSTANCE;
Constructor<EnumTest> declaredConstructor = EnumTest.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
EnumTest instance2 = declaredConstructor.newInstance();System.out.println(instance1);
System.out.println(instance2);}
运行 发现报错了 但是看报的错误和我们预期的不一样
并没有报出 newInstance 中抛出的异常:
Cannot reflectively create enum objects
而是 抛出了 没有这样的方法 的异常
难道是IDEA骗了我们?为什么不是无参构造方法 抛出没有这样的方法的异常?
通过百度查阅资料得到下面的结论
可以在上图中看出其实是有参构造的 而且参数是String 和 int
同样的方法通过反射来创建对象public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
EnumTest instance1 = EnumTest.INSTANCE;
Constructor<EnumTest> declaredConstructor =
EnumTest.class.getDeclaredConstructor(String.class,int.class);
declaredConstructor.setAccessible(true);
EnumTest instance2 = declaredConstructor.newInstance();System.out.println(instance1);
System.out.println(instance2);}
终于得到了预期的异常!!也就证明了不能通过反射来破坏枚举单例模式!请点个赞再走!!
原创:https://www.panoramacn.com
源码网提供WordPress源码,帝国CMS源码discuz源码,微信小程序,小说源码,杰奇源码,thinkphp源码,ecshop模板源码,微擎模板源码,dede源码,织梦源码等。专业搭建小说网站,小说程序,杰奇系列,微信小说系列,app系列小说
免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。
您必须遵守我们的协议,如果您下载了该资源行为将被视为对《免责声明》全部内容的认可-> 联系客服 投诉资源www.panoramacn.com资源全部来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。 敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:2640602276@qq.com未经允许不得转载:书荒源码源码网每日更新网站源码模板! » 单例模式是否真的线程安全之—-枚举
关注我们小说电影免费看关注我们,获取更多的全网素材资源,有趣有料!120000+人已关注
评论抢沙发