【问题标题】:java reflection :Avoid warning unchecked call to getConstructor(Class<?>...) as a member of the raw type Classjava反射:避免警告unchecked call to getConstructor(Class<?>...) 作为原始类型Class的成员
【发布时间】: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


【解决方案1】:

只需将循环声明更改为

for (Map.Entry<String, Class<?>> entry : connectionRepository.entrySet()) {

您遇到此错误是因为您使用参数化的Class 作为原始类型。 Here you can read about generics and wildcards。您可以使用Class&lt;?&gt; 并避免此错误。但是仍然需要转换为CWSConnection。您可以通过拥有 Map&lt;String, Class&lt;CWSConnection&gt;&gt; 而不是 Map&lt;String, Class&lt;?&gt;&gt; 来避免它。

【讨论】:

    【解决方案2】:

    方法

    Class.newInstance()
    

    调用类的默认构造函数。但我认为这对您的警告没有帮助,因为您的 Class 仍然是原始类型。

    【讨论】:

    • 这并不能真正回答问题;它可能更适合作为评论,因为问题的核心确实是警告。
    • @UweAllner “有没有更好的方法来获取默认构造函数”这部分对我来说已经足够了。 YMMV
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2016-10-22
    • 2011-11-27
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多