java反射:避免对getConstructor(类<?>…)的未经检查的警告调用作为原始类型类的成员
我读过这篇文章
java: unchecked call to getConstructor(java.lang.Class<?>...)
for (Map.Entry<String, Class> entry : connectionRepository.entrySet()) {
if (/*someconditionhere*/) {
try {
cwsConnection = (CWSConnection)entry.getValue().getConstructor().newInstance();
break;
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
logger.error("Could not Create instance of CWSConnection for site version:\"{}\" Error:\"{}\"", entry.getKey(), e.getMessage(), e);
}
}
}
在编译这段代码时,我得到了一个警告
warning: [unchecked] unchecked call to getConstructor(Class...) as a member of the raw type Class
我只是想获得CWSConnection的默认构造函数,因此,我不应该将任何参数传递给getConstructor(类…)方法 有没有更好的方法来获取默认构造函数(没有参数的构造函数)
(我知道@SupressWarning
注释将抑制此警告。)
# 1 楼答案
只需将循环声明更改为
出现此错误是因为使用ParameterSid
Class
作为原始类型Here you can read about generics and wildcards。您可以使用Class<?>
并避免此错误。但是仍然需要对CWSConnection
进行强制转换。你可以通过拥有一个Map<String, Class<CWSConnection>>
而不是Map<String, Class<?>>
来避免它# 2 楼答案
方法
调用类的默认构造函数。但我认为这对警告没有帮助,因为你的
Class
仍然是原始类型