2016-11-10 4 views
3

リフレクション(org.reflectionsで提供)を使用して、重い荷物を扱おうとしています。そのため、非常に長いリストのすべてのクラスのインスタンスを手動で作成する必要はありません。しかし、Reflectionsは私が期待していた方法でクラスをターゲットにしていないため、問題が発生しています。子クラスを使ったJavaのリフレクション

私の現在の反射コード:

Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".command.defaults"); 
Set<Class<? extends Command>> commandClasses = reflections.getSubTypesOf(Command.class); 

// Iterate through all the detected/found classes 
for (Class c : commandClasses) { 
    // If a class is abstract, ignore it. 
    if (Modifier.isAbstract(c.getModifiers())) { 
     continue; 
    } 

    // Attempt to create an instance of the class/command whatever. 
    try { 
     c.newInstance(); 
    } catch (InstantiationException | IllegalAccessException ex) { 
     // For once, the right thing to do is just ignore the exception. 
     // If a command is loaded but we can't create an instance or we 
     // can't access it, just skip. But, we'll at least log it (for now). 

     ex.printStackTrace(); 
    } 
} 

は基本的に、私のプログラムは、それらがただ視覚的グループ化のためのサブパッケージの数に分割しているcom.example.command.defaults、中に存在するすべてのコマンドがあります。各コマンドは独自のクラスにあり、com.example.commandPlayerCommandSimpleCommand、またはちょうどCommandの3つの抽象クラスのいずれかを拡張しています。 PlayerCommandおよびSimpleCommandCommandに拡張されます。

reflections.getSubTypesOf(Command.class)は、どのような方法でもCommandを拡張する任意のクラスを対象にすることができますが、そのようには動作していないようです。私のデバッガツールを使用して、ただ1つのクラス(ちょうどCommandに及ぶ)が実際にシステムによって読み込まれていることに気付きました。

Commandを継承するすべてのクラスと、Commandを継承するクラスを拡張するすべてのクラスをターゲットとしてReflectionsコードを作成するにはどうすればよいですか? APIドキュメントた内容に応じて、

+0

このライブラリのJavaドキュメントへのリンクはありますか? – markspace

+0

Googleはあなたにとってあまりにも多くのように見えるので、@ markspace ... http://static.javadoc.io/org.reflections/reflections/0.9.10/org/reflections/Reflections.html – BlackHatSamurai

+0

'PlayerCommand'と' SimpleCommand'は 'com.example.command'パッケージに入っていますので、' com.example.command.defaults'の代わりに 'com.example.command'をパッケージ名として使用してください。 –

答えて

0

getSubTypesOf(Class<T> type) は、特定のタイプの階層ですべてのサブタイプを取得しますが、それはまた、これは、「構成されたSubTypesScannerに依存」であることを統計します。

問題は、すべてのクラスがクラスローダーによってロードされていて、高度なクラスローダーによって認識されているわけではないため、結果リストにそのクラスが含まれていないことです。

関連する問題