泛型方法 - "unchecked conversion to conform to T from the type"警告



如果我有以下内容:

public interface Foo {
   <T extends Foo> T getBlah();
}
public class Bar implements Foo {
   public Bar getBlah() {  
      return this;
   }
}

我在eclipse中收到一个关于类Bar:中"getBlah"实现的警告

- Type safety: The return type Bar for getBlah from the type Bar needs unchecked conversion to conform to T from the type 
 Foo

我该怎么解决这个问题?为什么我会收到警告?

感谢

您正在重写接口中的一个方法,因此您的实现应该匹配规范中的签名:

public class Bar {
    @Override
    public <T extends Foo> T getBlah() {  
        return this;
    }
}

现在,如果您计划创建整个实现的特定参数化覆盖,那么您需要将泛型类型指定为接口定义的一部分:

public interface Foo<T extends Foo<T>> {
    T getBlah();
}
public class Bar implements Foo<Bar> {
   @Override
   public Bar getBlah() {  
      return this;
   }
}
<T extends Foo> T getBlah();

意味着调用者可以请求任何类型作为T返回。因此,无论对象是什么类,我都可以请求返回我选择的Foo的其他随机子类。这种方法唯一可以有效返回的值是null(除非它执行不安全的强制转换),这可能不是您想要的。

我不确定你想在这里完成什么,但我认为返回Foo是可以的:

interface Foo {
  public Foo getBlah();
}

因为您没有在参数中的任何位置使用泛型类型。

最新更新