预防反射攻击的方式是在私有构造函数过程中进行非null判断
//反射攻击
Constructor<HungrpSingleton> constructor = HungrpSingleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
HungrpSingleton s3 = constructor.newInstance();
HungrpSingleton s4 = HungrpSingleton.getInstance();
System.out.println(s3==s4);
class HungrpSingleton{
private static HungrpSingleton instance = new HungrpSingleton();
/**
* 私有化构造函数
*/
private HungrpSingleton() {
if (instance!=null){
throw new RuntimeException("单例不允许多实例");
}
}
public static HungrpSingleton getInstance(){
return instance;
}
}
网友评论