2012-10-22 38 views
10

如何獲取不安全類的實例?我總是得到安全例外。我列出了OpenJdk6實現的代碼。我想解決sun.misc.Unsafe爲我提供的函數,但我總是最終得到SecurityException Unsafe。如何獲取sun.misc.Unsafe的實例

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

請不要試圖告訴我使用這個類是多麼不安全。

回答

26

這應該給你比如不安全的:

@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); 
     } 
    }