Search code examples
javatypechecking

Java typechecking error in long "extends" chain


I am a bit baffled about Java type checking:

I have a static method declared as:

public static void register(EClass eClass, Class<? extends Page<EObject>> pClass) { ... }

I call it as:

Page.register(HyconmdePackage.Literals.STATION, StationPage.class);

where the second argument is declared as (forget about the first one: it's ok):

public class StationPage extends Page<Station> { ...
public abstract class Page<O> { ...
public interface Station extends Identifiable { ...
public interface Identifiable extends EObject { ...

but I get the error:

The method register(EClass, Class<? extends Page<EObject>>) in the type Page is not applicable for the arguments (EClass, Class<StationPage>)

I tried also declaring Page as:

public abstract class Page<O extends EObject> { ...

but the error remains and I have further problems in class Page.

What's my error? (I hope this is enough to guess the problem; trimming down program to size to have a working example would not be a trivial task)

TiA


Solution

  • StationPage extends Page<Station>, but your method signature requires it to extend Page<EObject>.

    Note that, even though Station (indirectly) extends EObject, this does not mean that Page<Station> extends Page<EObject>. So you cannot use Page<Station> when a Page<EObject> is expected.

    Declare the method like this:

    public static void register(EClass eClass,
        Class<? extends Page<? extends EObject>> pClass)
    

    You can ofcourse also use type parameters instead of wildcards:

    public static <P extends Page<E>, E extends EObject> register(EClass eClass,
        Class<P> pClass)