单例模式只允许一个类有一个实例对象,并且给定入口,反射的暴力破解方式不仅可以访问单例对象的私有方法,还能创建多个对象
单例对象
public class Singleton1 {
private static Singleton1 instance = new Singleton1();
private Singleton1(){
System.out.println("hello world!");
}
public static Singleton1 getInstance() {
return instance;
}
}
测试类
import java.lang.reflect.Constructor;
public class Test {
public static void main(String[] args) throws Exception{
Singleton1 s1 = Singleton1.getInstance();
Singleton1 s2 = Singleton1.getInstance();
System.out.println(s1 == s2);
@SuppressWarnings("unchecked")
Class<Singleton1> class1 = (Class<Singleton1>) Class .forName("fanshe.Singleton1");
Constructor<Singleton1> con = class1.getDeclaredConstructor(null);
con.setAccessible(true);
Singleton1 s3 = con.newInstance();
Singleton1 s4 = con.newInstance();
System.out.println(s3 == s4);
}
}