非常琐碎的Java问题。此代码有一个错误:
public abstract class SubTypeDependentEditor<T> implements Editor<T> {
protected abstract Editor<? extends T> getEditorFor(T obj);
public void edit(T obj) {
Editor<? extends T> editor = getEditorFor(obj);
editor.edit(obj); // ERROR IS HERE
}
}
修复它的正确方法是什么?
的想法T
基本上只是一种类的层次结构根,所以给定这样的层次结构:
class Entity {}
class EntityA extends Entity {}
class EntityB extends Entity {}
one 将T
设置为Entity
并getEditorFor(T obj)
负责返回Editor<X>
whereX
取决于obj
的具体类型,并且始终为 Is-A T
。所以,如果你有SubTypeDependentEditor<Entity>
,getEditorFor(T obj)
返回Editor<EntityA>
when obj
isEntityA
和Editor<EntityB>
when obj
is EntityB
。
这有没有可能在没有警告的情况下实施?
更新:
protected abstract Editor<? extends T> getEditorFor(T obj);
基本上可以有任何其他签名,但实现该代码的代码只有对象是Editor<X>
,所以如果这个方法返回Editor<T>
我不知道如何实现getEditorFor(T obj)
。