2016-12-02 40 views
2

我想能夠在我的項目中存儲每個類的數組。有沒有簡單的方法來做到這一點?如何獲取項目中現有類的列表?

Class<?>[] classes = SomeClass.getClasses(); 

謝謝。編輯: 這是主類的代碼。

package game_engine.main; 

public abstract class Main { 
    public static void main(String[]args){ 
     //do something 
    } 
    protected abstract void start(GameSettings settings); 
} 
+1

定義「每級」 –

+0

可不可以給一些見解,爲什麼你要這麼做? [XY問題](http://xyproblem.info/) – 4castle

+0

可能的重複[可以使用反射找到包中的所有類?](http://stackoverflow.com/q/520328/5221149) – Andreas

回答

0

有沒有簡單的方法來做到這一點,沒有。這樣做涉及到掃描類路徑,這是不可行的。 Google的Guava有ClassPath,但它明確表示不會將它用於生產關鍵任務。

0

我不能在單行代碼中完成它。但是,這也可能會有所幫助:

//scan urls that contain 'my.package', include inputs starting with 'my.package', use the default scanners 
Reflections reflections = new Reflections("my.package"); 

//or using ConfigurationBuilder 
new Reflections(new ConfigurationBuilder() 
.setUrls(ClasspathHelper.forPackage("my.project.prefix")) 
.setScanners(new SubTypesScanner(), 
       new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...), 
.filterInputsBy(new FilterBuilder().includePackage("my.project.prefix")) 
...); 

詳細信息:https://github.com/ronmamo/reflections

+0

我試過之前使用了反射,但它沒有從git中克隆,這些類不能被導入,並且它無法導入它。如何將github存儲庫添加到項目中? –

+0

你沒有使用maven或gradle? –

+0

不可以。你可以參考一個很好的教程嗎? –

相關問題