我看过这篇文章
java:unchecked调用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译这段代码时,我收到了警告
警告:[unchecked] unchecked调用getConstructor(Class ...)作为原始类型Class的成员
我只是想获得CWSConnection的默认构造函数,因此,我不应该将任何参数传递给getConstructor(Class ...)方法.有没有更好的方法来获取默认构造函数(没有参数的那个)
(我知道@SupressWarning注释会抑制此警告.)
只需将循环声明更改为
for (Map.Entry<String, Class<?>> entry : connectionRepository.entrySet()) {
Run Code Online (Sandbox Code Playgroud)
你有这个错误,因为你使用参数化Class作为原始类型.在这里,您可以阅读有关泛型和通配符的信息.您可以使用Class<?>并避免此错误.但CWSConnection仍然需要施法.你可以通过拥有Map<String, Class<CWSConnection>>而不是拥有它来避免它Map<String, Class<?>>.