Pretty trivial Java question. This code has an error:
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
}
}
What’s the right way one should fix it?
The idea of T is basically just a type of classes’ hierarchy root, so given a hierarchy like this:
class Entity {}
class EntityA extends Entity {}
class EntityB extends Entity {}
one will have T set to Entity and getEditorFor(T obj) is responsible for returning Editor<X> where X depends on obj‘s concrete type and always Is-A T. So, if you have SubTypeDependentEditor<Entity>, getEditorFor(T obj) returns Editor<EntityA> when obj is EntityA and Editor<EntityB> when obj is EntityB.
Any chance this can be implemented without warnings?
Update:
protected abstract Editor<? extends T> getEditorFor(T obj);
Can basically have any other signature, but the code that implements that code only has objects that are Editor<X>, so in case this method returns Editor<T> I’m not sure how to implement getEditorFor(T obj).
means that
getEditorFor()returns an editor for an unknown sub-type of T.You can’t pass use any value of type
Twith that result since the compiler cannot prove thatobjworks with the same concrete sub-type ofTthat isobj‘s type.The solution is to change
to
which says that
getEditorForreturns an editor that edits an unknown type that includesobj.