我已阅读此帖
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);
}
}
}
编译这段代码时,我收到警告
警告:[未选中]未经检查的调用getConstructor(Class ...)作为原始类型Class的成员
我只想获得CWSConnection的默认构造函数,因此,我不应该将任何参数传递给getConstructor(Class ...)方法。 有没有更好的方法来获取默认构造函数(没有参数的那个)
(我知道@SupressWarning
注释会抑制此警告。)
答案 0 :(得分:5)
只需将循环声明更改为
即可for (Map.Entry<String, Class<?>> entry : connectionRepository.entrySet()) {
您遇到此错误是因为您使用参数化Class
作为原始类型。 Here you can read about generics and wildcards。您可以使用Class<?>
并避免此错误。但仍然需要施放到CWSConnection
。您可以通过拥有Map<String, Class<CWSConnection>>
代替Map<String, Class<?>>
来避免它。
答案 1 :(得分:1)
方法
Class.newInstance()
调用该类的默认构造函数。但我认为这不会帮助您处理警告,因为您的Class
仍然是原始类型。