黑马程序员技术交流社区

标题: 防止通过反射来破坏单例模式 [打印本页]

作者: 瑞雪雄起    时间: 2015-10-24 01:35
标题: 防止通过反射来破坏单例模式
  1. package thread;

  2. import java.lang.reflect.Field;
  3. import sun.misc.Unsafe;
  4. public class Test {
  5.   
  6.          public static void main(String[] args) throws Exception {
  7.          System.out.println(A.flag);
  8.          new A();
  9.          new A();
  10.          System.out.println(A.flag);
  11.         }
  12.     }
  13. class A
  14. {
  15. public static final boolean flag=false;
  16. public A() throws Exception
  17. {
  18. if(getflag()) throw new Exception();       
  19. getUnsafe().putBooleanVolatile(A.class, getUnsafe().staticFieldOffset(A.class.getField("flag")), true);
  20. }
  21. private static final Unsafe getUnsafe()  
  22. {
  23. Unsafe unsafe=null;
  24. try{
  25. Field field= Unsafe.class.getDeclaredField("theUnsafe");
  26. field.setAccessible(true);
  27.   unsafe=(Unsafe)field.get(Unsafe.class);
  28.    }
  29. catch(Exception e){}
  30. return unsafe;
  31. }
  32. private static final boolean getflag()
  33. {
  34. boolean b = false;
  35.         try{
  36.        long start= getUnsafe().staticFieldOffset(A.class.getField("flag"));
  37.        b=getUnsafe().getBooleanVolatile(A.class, start);}
  38.         catch(Exception e){}
  39. return b;
  40. }
  41. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2