我有 NodeType
和 Node
的概念。 NodeType
是一堆元数据,您可以从中创建 Node
实例(很像整个类/对象关系)。
我有各种 NodeType
实现和各种 Node 实现。
在我的 AbstractNodeType(NodeTypes 的顶层)中,我有一个抽象的 createInstance()
方法,一旦由子类实现,它将创建正确的 Node 实例:
public abstract class AbstractNodeType {
// ..
public abstract <T extends AbstractNode> T createInstance();
}
在我的 NodeType
实现中,我实现了如下方法:
public class ThingType {
// ..
public Thing createInstance() {
return new Thing(/* .. */);
}
}
// FYI
public class Thing extends AbstractNode { /* .. */ }
这一切都很好,但是 public Thing createInstance()
会创建一个有关类型安全的警告。具体来说:
Type safety: The return type Thing for createInstance() from the type ThingType needs unchecked conversion to conform to T from the type AbstractNodeType
我做错了什么会导致这样的警告?
如何重构代码来解决此问题?
@SuppressWarnings("unchecked")
不好,我希望通过正确编码来解决此问题,而不是忽略问题!
最佳答案
您只需替换<T extends AbstractNode> T
即可与 AbstractNode
感谢 covariant returns 的魔力。 Java 5
添加了支持,但它没有得到应有的 pub。
关于java - 通用方法类型安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/81723/