2012-10-22 22 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); 
     } 
    } 
関連する問題