反射還可能會破壞單例模式,單例模式的特徵: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(); } } }