我如何获得sun.misc.Unsafe的实例

我如何获得不安全类的实例? 我总是得到安全例外。 我列出了OpenJdk6实现的代码。 我想把函数sun.misc.Unsafe提供给我,但我总是得到SecurityException不安全。

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

请不要试着告诉我使用这门课是多么不安全。

这应该给你不安全的实例:

 @SuppressWarnings("restriction") private static Unsafe getUnsafe() { try { Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe"); singleoneInstanceField.setAccessible(true); return (Unsafe) singleoneInstanceField.get(null); } catch (IllegalArgumentException e) { throw createExceptionForObtainingUnsafe(e); } catch (SecurityException e) { throw createExceptionForObtainingUnsafe(e); } catch (NoSuchFieldException e) { throw createExceptionForObtainingUnsafe(e); } catch (IllegalAccessException e) { throw createExceptionForObtainingUnsafe(e); } }