How do I get the instance of sun.misc.Unsafe?

百般思念 提交于 2019-12-09 14:21:54

问题


How do I get the instance of the unsafe class?

I always get the security exception. I listed the code of the OpenJDK 6 implementation. I would like to mess around with the function sun.misc.Unsafe offers to me, but I always end up getting the SecurityException("Unsafe").

public static Unsafe getUnsafe() {
    Class cc = sun.reflect.Reflection.getCallerClass(2);
    if (cc.getClassLoader() != null)
        throw new SecurityException("Unsafe");
    return theUnsafe;
}

(Please don't try to tell me how unsafe it is to use this class.)


回答1:


From baeldung.com, we can obtain the instance using reflection:

   Field f =Unsafe.class.getDeclaredField("theUnsafe");
   f.setAccessible(true);
   unsafe = (Unsafe) f.get(null);

Edit

The following is quoted from the description of the project where this code belongs to.

"The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven project, so it should be easy to import and run as it is."



来源:https://stackoverflow.com/questions/13003871/how-do-i-get-the-instance-of-sun-misc-unsafe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!