【发布时间】:2016-07-22 10:08:02
【问题描述】:
我看过这篇文章
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);
}
}
}
在编译这段代码时,我收到了一个警告
警告:[未选中] 作为原始类型 Class 的成员对 getConstructor(Class...) 的未选中调用
我只是想获取 CWSConnection 的默认构造函数,因此,我不应该将任何参数传递给 getConstructor(Class...) 方法。 有没有更好的方法来获取默认构造函数(没有参数的那个)
(我知道@SupressWarning 注释会抑制这个警告。)
【问题讨论】:
-
你也可以试试 CWSConnection.class.cast(entry.getValue().getConstructor().newInstance());
-
已尝试但仍收到警告
-
好吧:类> klass = entry.getValue();构造函数> 构造函数 = klass.getConstructor(); cwsConnection = constructor.newInstance();
-
效果很好
标签: java reflection