1. 程式人生 > >單例模式破解之反射

單例模式破解之反射

單例模式只允許一個類有一個例項物件,並且給定入口,反射的暴力破解方式不僅可以訪問單例物件的私有方法,還能建立多個物件

單例物件

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);
	}
}