Java generics: why someObject.getClass() doesn't return Class<? extends T>?

java.is.for.desktop picture java.is.for.desktop · Dec 16, 2010 · Viewed 8.7k times · Source

I would expect that from the aspect of compile time as well as from the aspect of runtime it wouldn't be a problem for .getClass() to provide a correctly-typed return value.

But I must be wrong.

public class _GetClassGenerics2 {

  static class MyClass {
  }

  public static void main(String[] args) {
    MyClass myInstance = new MyClass();
    // here it works
    Class<? extends MyClass> type = myInstance.getClass();

    myMethod(myInstance);
  }

  public static <T extends MyClass> void myMethod(T instance) {
    Class<? extends T> type = instance.getClass();
// java.lang.RuntimeException: Uncompilable source code - incompatible types
//  required: java.lang.Class<? extends T>
//  found:    java.lang.Class<capture#1 of ? extends _GetClassGenerics2.MyClass>
  }

}

EDIT: It doesn't work with Class<T> and Class<? super T> either.

Answer

Tom Hawtin - tackline picture Tom Hawtin - tackline · Dec 16, 2010

java.lang.Class does not represent a type (use java.lang.reflect.Type for that). If T, were say ArrayList<String> then it makes no sense for there to be a Class<ArrayList<String>>.

It's worth noting that in this particular case there is no need for the method to be generic.

public static <T extends MyClass> void myMethod(T instance) {

Is equivalent to:

public static void myMethod(MyClass instance) {