2013-04-12 55 views
0

如何獲取使用反射的.java文件的所有類名稱。Java反射獲取多個類

當我運行下面的代碼它只打印出船。我曾試圖使像類的數組:

Class c[] = Class.forName("boat.Boat") 

,但它會導致一個語法錯誤

public class Reflection { 
public static void main(String[] args) { 
    try {   
     Class c = Class.forName("boat.Boat"); 
     System.out.println(c.getSimpleName()); 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } 
    } 
} 

Boat.java

package boat; 
public class Boat extends Vehicle { 
    public Boat() {} 
} 

class Vehicle { 
    public Vehicle() { 
     name = ""; 
    } 
    private name; 
} 
+0

如果不讀取Java源文件並以這種方式進行解析,就無法據我所知。一旦該類被編譯,它就不會保留源文件位置的知識。你可以做出一些有教育意義的猜測,就像公共類可能來自一個類似名稱的Java源文件,但你甚至不能爲非公開類做這些。 –

回答

2

即使你在一個寫多個類.java文件(只有一個公共類),您將獲得多個.class文件。因此,您無法從.java文件獲取類的列表。

您可以選擇編寫自定義分析器來分析.java文件並檢索類名稱。不知道那會是什麼用途?

0

您可以通過Class對象上調用getSuperclass()得到Boat類的父類:

Class<?> c = Boat.class; 

Class<?> superClass = c.getSuperclass(); 
System.out.println(superClass.getSimpleName()); // will print: Vehicle 

看爲java.lang.Class API文檔。

0

這是.class文件,我們在Class.forName("");沒有提供。 java文件。因此,沒有規定使用Class.forName()方法從.java文件獲取所有類。

0

如果你願意使用額外的庫,你可以使用反射項目,允許你搜索包中列出的類。

Reflections reflections = new Reflections("my.package.prefix"); 
//or 
Reflections reflections = new Reflections(ClasspathHelper.forPackage("my.package.prefix"), 
     new SubTypesScanner(), new TypesAnnotationScanner(), new FilterBuilder().includePackage(...), ...); 

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

//then query, for example: 
Set<Class<? extends Module>> modules = reflections.getSubTypesOf(com.google.inject.Module.class); 
Set<Class<?>> singletons =    reflections.getTypesAnnotatedWith(javax.inject.Singleton.class); 

Set<String> properties =  reflections.getResources(Pattern.compile(".*\\.properties")); 
Set<Constructor> injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class); 
Set<Method> deprecateds =  reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class); 
Set<Field> ids =    reflections.getFieldsAnnotatedWith(javax.persistence.Id.class); 

Set<Method> someMethods =  reflections.getMethodsMatchParams(long.class, int.class); 
Set<Method> voidMethods =  reflections.getMethodsReturn(void.class); 
Set<Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class); 
Set<Method> floatToString = reflections.getConverters(Float.class, String.class); 

正如你所看到的,你可以用不同的過濾器進行搜索。我不認爲你不能爲java文件做,但你可以搜索包名稱的所有類。