[英]Java reflection to get multiple classes
如何使用反射獲取.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;
}
即使您在單個.java文件中編寫多個類(只有一個公共類),您將獲得多個.class文件。 因此,您無法從.java文件中獲取類列表。
您可以選擇編寫自定義解析器來解析.java文件並檢索類名。 不確定會有什么用?
您可以通過在Class
對象上調用getSuperclass()
來獲取類Boat
的超類:
Class<?> c = Boat.class;
Class<?> superClass = c.getSuperclass();
System.out.println(superClass.getSimpleName()); // will print: Vehicle
查看java.lang.Class的API文檔。
它是我們在Class.forName("");
中提供的.class
文件Class.forName("");
沒有。 java
文件。 因此,沒有規定使用Class.forName()
方法從.java文件中獲取所有類。
如果您願意使用其他庫,則可以使用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);
如您所見,您可以使用不同的過濾器進行搜索。 我不認為你不能為java文件做,但你可以搜索所有類的包名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.