2012-10-22 3 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); 
     } 
    } 
관련 문제