我有我想要使用加載類,並在運行時實例化我的對象的靜態方法,但是當我編譯,我得到這樣的警告:如何將通配符(?)轉換爲泛型類型T?
warning: [unchecked] unchecked cast
T t = (T) ctor.newInstance();
required: T
found: CAP#1
where T is a type-variable:
T extends Object declared in method <T>forName(String,Set<String>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
1 warning
下面的代碼:
public static <T> Set<T> forName(String modulePath, Set<String> classes) throws InvalidModuleException{
try {
ClassLoader cl = new URLClassLoader(new URL[]{new URL(modulePath)});
Set<T> list = new HashSet<>(classes.size());
for (String className : classes) {
Class<?> clazz = (Class<?>) Class.forName(className, true, cl);
Constructor<?> ctor = clazz.getConstructor();
T t = (T) ctor.newInstance();
list.add(t);
}
return list;
} catch (MalformedURLException | ReflectiveOperationException ex) {
throw new InvalidModuleException(ex.getMessage());
}
}
有人可以解釋我嗎?
[更新] 這裏是和實例方法調用:
HashSet<String> set = new HashSet<>();
h.add("fully_classfied_classname_readed_from_file"); //Class that extends AbstractApplication
Set<AbstractApplication> abs = Apps.forName("plugins/module.jar", set);
這就是我想要的。加載子類(請參閱更新)。我想你的代碼可以幫助。 – ehbarbian
或者,您可以事先更改類的類型Class extends T> clazz = Class.forName(...)。asSubclass(claz);' – newacct