【问题标题】:How to resolve warning: References to generic type should be parameterised如何解决警告:对泛型类型的引用应参数化
【发布时间】:2020-02-04 13:12:06
【问题描述】:

我已经创建了通用接口。

public interface Abc<T> {
    void validatePojo(T input);
}

以下两个类是上述接口的实现。

1)-----------------------------------------------
  public class Hello implements Abc<Pojo1> {
       @Override
       public void validatePojo(Pojo1 input) {
          // some code
       }
  }
2)-----------------------------------------------
  public class Hi implements Abc<Pojo2> {
       @Override
       public void validatePojo(Pojo2 input) {
          // some code
       }
   }

现在当我尝试创建 Abc 的对象时,

T input = getInput(someInput);    // getInput return either Pojo1 or Pojo2
Abc abc = someFactory(someInput); //someFactory(someInput) will return either `new Hello()` 
  ^                               //or `new Hi()` based on `someInput`
  |
  +-------------------------------//warning
abc.validate(input);

public Abc<?> someFactory(final int input) {
    return input == 1 ? new Hi() : new Hello();
}

public T getInput(final int input) {
    return input == 1 ? new Pojo1() : new Pojo2();
}

我开始担心Abc is a raw type. References to generic type Abc&lt;T&gt; should be parameterized

我怎样才能重新接受这个警告?

我在网上找了以下,但不是很有用。

  1. 我发现的一种方法是使用@SuppressWarnings
  2. 声明变量Abc&lt;Pojo1&gt; abcAbc&lt;Pojo2&gt; abc,我不能这样做,因为使用Pojo1或Pojo2完全取决于输入。(我不想在这里写工厂方法的逻辑)

有没有其他方法可以重新爱上它?

【问题讨论】:

  • 可能是Abc&lt;?&gt;?此外,您在第二个 sn-p 中显示的声明没有意义。为什么Hello 有两个声明?为什么Hello 自己实现? Hi 是什么?
  • @Sweeper 我的错。编辑了问题。
  • 使用Abc&lt;?&gt; 作为abc 的类型是否有效?
  • @yajiv 正如 Sweeper 提到的,你应该使用通配符 Abc> 这意味着 Abc

标签: java generics interface warnings interface-implementation


【解决方案1】:

编译器只是通知您,Abc 是通用的,并且取决于您在工厂中传递的类型。 因此:

Abc<?> abc = ...
Abc<? extends Object> abc = ...

如 cmets 中所述,应该是有效的。如果您想指定传递的对象类型,则扩展版本很有用。

【讨论】:

  • 如果我使用 Abc> 那么我收到 abc.validatePojo(input) 的错误。说 Abc 类型的方法 validatePojo(capture#2-of ?) 不适用于参数 (T)。这里假设输入是 Pojo1 或 Pojo2。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
相关资源
最近更新 更多