【发布时间】: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<T> should be parameterized。
我怎样才能重新接受这个警告?
我在网上找了以下,但不是很有用。
- 我发现的一种方法是使用
@SuppressWarnings。 - 声明变量
Abc<Pojo1> abc或Abc<Pojo2> abc,我不能这样做,因为使用Pojo1或Pojo2完全取决于输入。(我不想在这里写工厂方法的逻辑)
有没有其他方法可以重新爱上它?
【问题讨论】:
-
可能是
Abc<?>?此外,您在第二个 sn-p 中显示的声明没有意义。为什么Hello有两个声明?为什么Hello自己实现?Hi是什么? -
@Sweeper 我的错。编辑了问题。
-
使用
Abc<?>作为abc的类型是否有效? -
@yajiv 正如 Sweeper 提到的,你应该使用通配符 Abc> 这意味着 Abc
标签: java generics interface warnings interface-implementation