反射还可能会破坏单例模式,单例模式的特征:java
以懒汉模式为例,看一下反射如何破坏单例模式code
懒汉单例模式代码:get
public class Lazy { private static Lazy instance; private Lazy(){ } public static Lazy getInstance(){ if (instance==null){ synchronized (Lazy.class){ if (instance==null){ instance=new Lazy(); } } } return instance; } }
破坏单例模式:io
public class SingletonDestory { public static void main(String[] args) { Lazy lazyInstance=Lazy.getInstance(); try { Constructor declaredConstructor = Lazy.class.getDeclaredConstructor(null); declaredConstructor.setAccessible(true); //设置私有的构造器,强制访问 Lazy lazyInstance2= (Lazy) declaredConstructor.newInstance(); System.out.println(lazyInstance==lazyInstance2); //嘿嘿,不是一个实例 } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }