Generics in return types of static methods and inheritance
- by Axel
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.