2013-04-12 57 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文件做,但你可以搜索包名称的所有类。