views:

64

answers:

4

I have the following class

public class MyClass<T> {
    public Class<T> getDomainClass() {
          GET THE CLASS OF T
    }
}

I've googled this problem and all the answers I could find told me to use getGenericSuperClass(), but the problem of this method is that I must have a second class that extends MyClass and I don't want to do this. What I need is to get the parametrized type of a concrete class?

+3  A: 

You can't. The information you want (i.e. the value of T) is not available at run-time due to type-erasure.

sepp2k
A: 

If you need to know the type you probably shouldn't be using generics.

Finbarr
+2  A: 

Due to type erasure, the only way to get it is if it is passed as an explicit parameter - either in a method, or in the constructor.

public class MyClass<T> {
    public Class<T> getDomainClass(Class<T> theClass) {
          // use theClass
    }
}
Péter Török
+1  A: 

The only way I know of:

public class MyClass<T> {

    private Class<T> clazz;

    public MyClass(Class<T> clazz) {
       this.clazz = clazz;
    }

    public Class<T> getDomainClass() {
      return clazz;
    }
}

So you basically provide the runtime the info, it doesn't have from the compiler.

Chris Lercher