我有一个静态方法,想在运行时使用它来加载类并实例化我的对象,但是当我编译时,出现了这个警告:
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);