2009-05-04 3 views
0

질문 : 내 응용 프로그램에서 몇 가지 성능 문제가액세스 비공개 클래스 [특별히 : FetcherInfo]

- 그리고 병목 sun.awt.image.ImageFetcher.run이고, I는 (더 얻을 canno't) profiler에서 의미있는 정보. 그래서 나는 ImageFetcher가하고있는 일을 보는 것이 좋을 것이라고 생각했습니다.

모든 ImageFetcher 개의 작업을 보유하고있는 FetcherInfo 클래스에 액세스하지 못했습니다. FetcherInfo 인스턴스를 얻으려면 FetcherInfo.getFetcherInfo()으로 전화해야합니다.

나는 패키지 sun.awt.image (단지 내 프로젝트에서, 나는 rt.jar로 팅커를하지 않았다)에서 클래스를 생성했다.

try{ 
    for(Method method : FetcherInfo.class.getDeclaredMethods()){ 
     method.setAccessible(true); 
     if(method.getName().equals("getFetcherInfo")){ 
     m = method; 
     } 
    } 
}catch (Exception e){ 
    e.printStackTrace(); 
} 

FetcherInfo info = null; 
try { 
    info = (FetcherInfo) m.invoke(null); 
} catch (IllegalAccessException e) { 
    e.printStackTrace(); 
} catch (InvocationTargetException e) { 
    e.printStackTrace(); 
} 

그리고 나는 예외를 얻을 :

FetcherInfo을 얻으려면 내가 사용에 Exception in thread "IMAGE-FETCHER-WATCHER" java.lang.IllegalAccessError: tried to access class sun.awt.image.FetcherInfo from class sun.awt.image.FetcherDebug

그리고 스택 트레이스 포인트 :

for(Method method : FetcherInfo.class.getDeclaredMethods()){ 

이 같은 예외가 제기되었다

FetcherInfo.class.getMethod("getFetcherInfo"); 

그래서 누구 하나하는 방법에 어떤 아이디어를 가지고 :

  • 이미지가로드지고있는 것을 알아 ImageFetcher 예를
  • 을 확보

솔루션

문제는 내가 '이었다 내 클래스를 sun.java.awt 패키지에 넣고 보호 된 멤버를 액세스하려면 rt.jar에 넣지 말고 except 형은 ImageFetcher.class라고하는 암탉을 던졌습니다.

답변

2

액세스 할 수없는 멤버에게 액세스하려면 setAccessible(true)을 사용하십시오. (시큐리티 매니저가 존재하지 않고, 반사와 함께 사용되는 sun.* 클래스에 대한 더 블록이 없다.) 당신이 방법 # setAccessible을 의미하는 경우 나에 접근하기 전에

import java.lang.reflect.Method; 

public class Access { 
    public static void main(String[] args) throws Exception { 
     Class<?> imageFetcher = Class.forName("sun.awt.image.FetcherInfo"); 
     for (Method method : imageFetcher.getDeclaredMethods()) { 
      ; 
     } 
     Method method = imageFetcher.getDeclaredMethod("getFetcherInfo"); 
     method.setAccessible(true); 
     Object fetcher = method.invoke(null); 
     System.err.println(fetcher); 
    } 
} 
+0

, 난 예외가 발생하기 때문에, 그것을 할 수 없습니다 메소드 인스턴스 (FetcherInfo.class.getDeclaredMethods() 호출시 occure됩니다). –

+1

저에게 맞습니다! 이상하게 여겨요? 문제를 보여주는 작지만 완전한 예제를 작성할 수 있습니까? –

+0

벙어리, 바보, 벙어리. 모든 작업이 지금 :) 문제는 FetcherInfo.class를 호출하고있었습니다. –