java反射:避免警告未经检查的getConstructor调用(Class <! - ? - > ...)作为原始类型Class的成员

时间:2016-07-22 10:08:03

标签: java reflection

我已阅读此帖

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注释会抑制此警告。)

2 个答案:

答案 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仍然是原始类型。

相关问题