反射(三)
反射还可能会破坏单例模式,单例模式的特征:
- 私有化构造方法
- 提供全局唯一的公有访问点
以懒汉模式为例,看一下反射如何破坏单例模式
懒汉单例模式代码:
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;
}
}
破坏单例模式:
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();
}
}
}
网友评论