【发布时间】:2016-01-13 12:37:41
【问题描述】:
我有一个静态方法,我想用它来加载类并在运行时实例化我的对象,但是当我编译时,我收到了这个警告:
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);
【问题讨论】:
标签: java generics casting wildcard