单例是真正意义上的单例吗?我们下面先上单例代码
public class Sington { private static volatile Sington sington; private Sington(){} public static Sington getSington(){ if(sington==null){ synchronized (Sington.class){ if(sington==null){ sington = new Sington(); } } } return sington; }}
测试一下
下面呢,我们就基于反射来破解单例,当然破解方式不止一种。
public static void main(String[] args) throws Exception { Sington sington = Sington.getSington(); Sington sington1 = Sington.getSington(); System.out.println(sington==sington1); Class<?> aClass = Class.forName("com.mayikt.Sington"); Constructor<?> constructor = aClass.getDeclaredConstructor(null); constructor.setAccessible(true); Sington sington2 = (Sington)constructor.newInstance(); System.out.println(sington==sington2);}
所以你学会了吗?