黑马程序员技术交流社区
标题:
防止通过反射来破坏单例模式
[打印本页]
作者:
瑞雪雄起
时间:
2015-10-24 01:35
标题:
防止通过反射来破坏单例模式
package thread;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(A.flag);
new A();
new A();
System.out.println(A.flag);
}
}
class A
{
public static final boolean flag=false;
public A() throws Exception
{
if(getflag()) throw new Exception();
getUnsafe().putBooleanVolatile(A.class, getUnsafe().staticFieldOffset(A.class.getField("flag")), true);
}
private static final Unsafe getUnsafe()
{
Unsafe unsafe=null;
try{
Field field= Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe=(Unsafe)field.get(Unsafe.class);
}
catch(Exception e){}
return unsafe;
}
private static final boolean getflag()
{
boolean b = false;
try{
long start= getUnsafe().staticFieldOffset(A.class.getField("flag"));
b=getUnsafe().getBooleanVolatile(A.class, start);}
catch(Exception e){}
return b;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2