通用方法 - "未经检查的转换以符合类型中的T"警告

Joe*_*dev 8 java generics

如果我有以下内容:

public interface Foo {
   <T extends Foo> T getBlah();
}

public class Bar implements Foo {
   public Bar getBlah() {  
      return this;
   }
}
Run Code Online (Sandbox Code Playgroud)

我在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
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Per*_*ion 14

您正在从您的界面覆盖方法,因此您的实现应该与您的规范中的签名匹配:

public class Bar {
    @Override
    public <T extends Foo> T getBlah() {  
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public interface Foo<T extends Foo<T>> {
    T getBlah();
}

public class Bar implements Foo<Bar> {
   @Override
   public Bar getBlah() {  
      return this;
   }
}
Run Code Online (Sandbox Code Playgroud)