我正在尝试在以下位置找到的反射库:https://code.google.com/p/reflections/
我想要实现的目标是扫描项目中的包,然后创建在该包中找到的给定类型的所有子类的实例。 我使用该库的方式是正确的,因为 subTypes 返回以下内容:
[class identifiers.DNSLookup, class identifiers.AliasChecker, class identifiers.GoogleSafeBrowsing]
尽管我的问题是如何创建该集合中找到的类的新实例。它们都有无参构造函数。
private void getDetectors(){
Reflections reflections = new Reflections("identifiers"); //name of package to scan
Set<Class<? extends DetectorSub>> subTypes =
reflections.getSubTypesOf(DetectorSub.class);
System.out.println(subTypes); // correct classes included here.
for(Class<? extends DetectorSub> detector:subTypes){
try {
DetectorSub d =(DetectorSub)detector.getClass().newInstance().cast(DetectorSub.class); //returns exceptions at runtime.
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
上面的代码返回以下异常:
java.lang.IllegalAccessException: Can not call newInstance() on the Class for java.lang.Class
at java.lang.Class.newInstance0(Class.java:339)
at java.lang.Class.newInstance(Class.java:327)
at core.PhishingScanner.getDetectors(PhishingScanner.java:40)
at core.PhishingScanner.<init>(PhishingScanner.java:28)
at core.Main.main(Main.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
最后一点,是否可以使用上述功能根据类的接口(interface)而不是父类(super class)来扫描类?谢谢。
最佳答案
在您的代码中:
for(Class<? extends DetectorSub> detector:subTypes){
这里detector
是 Class<? extends DetectorSub>
的一个实例
然后:
DetectorSub d =(DetectorSub)detector.getClass().newInstance().cast(DetectorSub.class);
您正在调用getClass()
上detector
,也就是说您正在 Class<? extends DetectorSub>
上调用 getClass()实例并获得代表 Class
的类对象而不是 DetectorSub
的子类型不再了。因此,当您创建新实例时,您实际上是在尝试创建 Class
的新实例。 ,这会失败,因为 Class
的默认构造函数是私有(private)的。
你应该这样写:
DetectorSub d = detector.newInstance();
关于java - 使用 Reflections 创建新的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15189407/