java反射,破坏单例模式
静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
反射实例化单例
public void attackSingleton() {
Class<?> singletonClass = Singleton.class;
try {
Constructor<?>[] constructors = singletonClass.getDeclaredConstructors();
constructors[0].setAccessible(true);
Singleton instance1 = (Singleton) constructors[0].newInstance();
Singleton instance2 = (Singleton) constructors[0].newInstance();
if (instance1 == instance2) {
System.out.println("attack failed,攻击Sinleton5失败");
} else {
System.out.println("attack success!攻击Sinleton5成功,创建了多个实例");
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
网友评论