通用方法 - “未检查的转换符合T从类型”警告 [英] Generic method - "unchecked conversion to conform to T from the type" warning
问题描述
如果我有以下内容:
public interface Foo {
< T extends Foo> T getBlah();
}
public class Bar实现Foo {
public Bar getBlah(){
return this;
$ b我在eclipse中得到了关于'getBlah'在类Bar中的实现:
- 类型安全性:类型栏中getBlah的返回类型Bar需要未经检查的转换以符合T从类型
Foo
我该如何解决这个问题?为什么我会收到警告?
谢谢 您 从你的接口覆盖一个方法,所以你的实现应该匹配你的规范签名: $ b @Override
public< T extends Foo> T getBlah(){
返回这个;
$ / code $ / pre
现在,如果你打算创建一个专门的然后您需要将泛型类型指定为接口定义的一部分:
public interface Foo< ; T延伸Foo< T> {
T getBlah();
}
public class Bar实现Foo< Bar> {
@Override
public Bar getBlah(){
return this;
}
}
If I have the following:
public interface Foo {
<T extends Foo> T getBlah();
}
public class Bar implements Foo {
public Bar getBlah() {
return this;
}
}
I get a warning in eclipse about the 'getBlah' implementation in class Bar:
- Type safety: The return type Bar for getBlah from the type Bar needs unchecked conversion to conform to T from the type
Foo
How can I fix this? And why am I getting the warning?
Thanks
解决方案 You are overriding a method from your interface, so your implementation you should match the signature from your specification:
public class Bar {
@Override
public <T extends Foo> T getBlah() {
return this;
}
}
Now, if you were instead planning on creating a specifically parametized override of the entire implementation, then you need to specify the generic type as a part of the interface definition:
public interface Foo<T extends Foo<T>> {
T getBlah();
}
public class Bar implements Foo<Bar> {
@Override
public Bar getBlah() {
return this;
}
}
这篇关于通用方法 - “未检查的转换符合T从类型”警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!