2009-05-04 4 views
0

質問:私は私のアプリではいくつかのパフォーマンスの問題を抱えているアクセスは、非publicクラス[特別:FetcherInfo]

- とボトルネックはsun.awt.image.ImageFetcher.runある、と私は(多くを得るcanno't )プロファイラから意味のある情報。だから私は、ImageFetcherがやっている仕事を見てうれしいと思った。

ImageFetcherのジョブをすべて保持しているFetcherInfoクラスにアクセスできませんでした。 FetcherInfoのインスタンスを取得するには、FetcherInfo.getFetcherInfo()に電話する必要があります。

私はパッケージsun.awt.imageのクラスを作成しました(私のプロジェクトでは、rt.jarを使っていませんでした)。

私が使用FetcherInfoを取得するには:

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

そして、私は例外を取得:へ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インスタンス
  • を入手

SOLUTION

問題は、i」はということでした私のクラスをsun.java.awtパッケージに入れて、保護されたメンバーをrt.jarに入れずにパッケージにアクセスし、excep鶏はImageFetcher.classと呼んでいます。

答えて

2

アクセスできないメンバーにアクセスするには、setAccessible(true)を使用してください。 (セキュリティマネージャが存在しない、反射で使用されているからsun.*クラス上のブロックがない。)

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

あなたは方法#setAccessibleを意味している場合、私はへのアクセスを取得する前に、例外がスローされているので、私は、それを行うことはできませんメソッドインスタンス(FetcherInfo.class.getDeclaredMethods()の呼び出し時に発生します)。 –

+1

私のために働く!あなたは何をしていますか奇妙ですか?この問題を示す小さな完全な例を書くことができますか? –

+0

ダム、ダム、ダム私。 すべて動作します:)問題はFetcherInfo.classを呼び出していました。 –