7

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?

IAdapter
  • 62,595
  • 73
  • 179
  • 242
GuidoMB
  • 2,191
  • 3
  • 25
  • 40
  • Did you see: http://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection ? – Campa Sep 04 '15 at 10:53

5 Answers5

5

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

sepp2k
  • 363,768
  • 54
  • 674
  • 675
3

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
  • 114,404
  • 31
  • 268
  • 329
3

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
  • 37,264
  • 20
  • 99
  • 131
1

You can do it if you want to get a generic type you inherit! Add this method to your class and profit! ;)

public Class<?> getGenericType() {
    Class result = null;
    Type type = this.getClass().getGenericSuperclass();

    if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type[] fieldArgTypes = pt.getActualTypeArguments();
        result = (Class) fieldArgTypes[0];
    }

    return result;
}
Manuel Araoz
  • 15,962
  • 24
  • 71
  • 95
0

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

Finbarr
  • 31,350
  • 13
  • 63
  • 94