Generics in return types of static methods and inheritance

Posted by Axel on Stack Overflow See other posts from Stack Overflow or by Axel
Published on 2012-11-23T17:02:04Z Indexed on 2012/11/23 17:04 UTC
Read the original article Hit count: 196

Generics in return types of static methods do not seem to get along well with inheritance. Please take a look at the following code:

class ClassInfo<C>  {
  public ClassInfo(Class<C> clazz) {
    this(clazz,null);
  }  
  public ClassInfo(Class<C> clazz, ClassInfo<? super C> superClassInfo) {
  }
}

class A {
    public static ClassInfo<A> getClassInfo() {
        return new ClassInfo<A>(A.class);
    }
}

class B extends A {
    // Error: The return type is incompatible with A.getClassInfo()
    public static ClassInfo<B> getClassInfo() { 
        return new ClassInfo<B>(B.class, A.getClassInfo());
    }
}

I tried to circumvent this by changing the return type for A.getClassInfo(), and now the error pops up at another location:

class ClassInfo<C>  {
  public ClassInfo(Class<C> clazz) {
    this(clazz,null);
  }  
  public ClassInfo(Class<C> clazz, ClassInfo<? super C> superClassInfo) {
  }
}

class A {
    public static ClassInfo<? extends A> getClassInfo() {
        return new ClassInfo<A>(A.class);
    }
}

class B extends A {
    public static ClassInfo<? extends B> getClassInfo() { 
        // Error: The constructor ClassInfo<B>(Class<B>, ClassInfo<capture#1-of ? extends A>) is undefined
        return new ClassInfo<B>(B.class, A.getClassInfo());
    }
}

What is the reason for this strict checking on static methods? And how can I get along? Changing the method name seems awkward.

© Stack Overflow or respective owner

Related posts about java

Related posts about generics