(一)通过反射破解
注:其中StrengthSingleDemo02为上一篇发表的单例设计模式的---懒汉式
这里之所以写成这样是因为下一篇将发表怎么防止破解(反射和反序列化)的方法
import java.io.*;
import java.lang.reflect.Constructor;
public class BrokenSingletonDemo {
public static void main(String[] args)throws Exception {
// 反射破解懒汉式
StrengthSingleDemo02 s1 = StrengthSingleDemo02.getInstance();
StrengthSingleDemo02 s2 = StrengthSingleDemo02.getInstance();
System.out.println(s1);
System.out.println(s2);
// 1.通过反射直接访问私有构造器
Class<SingletonDemo02> clazz = (Class<SingletonDemo02>)Class.forName("com.ly.Singleton.SingletonDemo02");
Constructor<SingletonDemo02> c = clazz.getDeclaredConstructor();
c.setAccessible(true); // 不加的话IllegalAccessException:非法访问
SingletonDemo02 s4 = c.newInstance();
SingletonDemo02 s5 = c.newInstance();
System.out.println(s4);
System.out.println(s5);
/*运行结果
* com.ly.Singleton.SingletonDemo02@677327b6
com.ly.Singleton.SingletonDemo02@14ae5a5
*/
}
}
(二)通过反序列化破解
import java.io.*;
import java.lang.reflect.Constructor;
public class BrokenSingletonDemo {
public static void main(String[] args)throws Exception {
StrengthSingleDemo02 s1 = StrengthSingleDemo02.getInstance();
StrengthSingleDemo02 s2 = StrengthSingleDemo02.getInstance();
System.out.println(s1);
System.out.println(s2);
//2.通过序列化和反序列化破解单例
File file = new File("SingletonBrokenBySerializ.txt");
try{
file.createNewFile();
}catch(Exception e){
e.printStackTrace();
}
// 序列化过程
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.close();
fos.close();
// 反序列化过程
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
StrengthSingleDemo02 s4 = (StrengthSingleDemo02) ois.readObject();
System.out.println(s4);
/*
* // 运行结果
* com.ly.Singleton.StrengthSingleDemo02@1540e19d
com.ly.Singleton.StrengthSingleDemo02@1540e19d
com.ly.Singleton.StrengthSingleDemo02@58372a00
* */
}
}