简体   繁体   English

Java反射获取多个类

[英]Java reflection to get multiple classes

How do i get all of the class names for a .java file using reflection. 如何使用反射获取.java文件的所有类名。

When i run the following code it only prints out Boat. 当我运行以下代码时,它只打印出船。 I have tried making an array of Classes like: 我试过制作一个类数组,如:

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

but it results in a syntax error 但它会导致语法错误

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 Boat.java

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

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

Even if you write multiple classes in a single .java file (with only one public class), you will get multiple .class files. 即使您在单个.java文件中编写多个类(只有一个公共类),您将获得多个.class文件。 Hence, you cannot get the list of classes from .java file. 因此,您无法从.java文件中获取类列表。

You do have an option of writing a custom parser to parse the .java file and retrieve the class names. 您可以选择编写自定义解析器来解析.java文件并检索类名。 Not sure what would be the use of that? 不确定会有什么用?

You can get the superclass of class Boat by calling getSuperclass() on the Class object: 您可以通过在Class对象上调用getSuperclass()来获取类Boat的超类:

Class<?> c = Boat.class;

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

Look at the API documentation for java.lang.Class . 查看java.lang.Class的API文档。

It is the .class file we are providing in Class.forName(""); 它是我们在Class.forName("");中提供的.class文件Class.forName(""); not . 没有。 java file. java文件。 So there is no provision to get all classes from .java file with the usage of Class.forName() method. 因此,没有规定使用Class.forName()方法从.java文件中获取所有类。

If you are willing to use additional libraries you can use Reflections Project that allows you to search for classes listed in a package. 如果您愿意使用其他库,则可以使用Reflections Project来搜索包中列出的类。

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

As you can see you can search with different filters. 如您所见,您可以使用不同的过滤器进行搜索。 I don't think you can't do for java file but you can search all the classes for package name. 我不认为你不能为java文件做,但你可以搜索所有类的包名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM