Getting the type of a parameterized class parameter?

I have the following class

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

I searched for this problem and all the answers that I could find told me to use getGenericSuperClass (), but the problem with this method is that I have to have a second class that extends MyClass and I don't want to do this, I need to get the parameterized type of a particular class?

+7
java generics reflection
source share
5 answers

You can not. The information you want (i.e. the value of T) is not available at runtime due to type erasure.

+5
source share

Due to erasing styles, the only way to get this is to pass it as an explicit parameter - either in the method or in the constructor.

 public class MyClass<T> { public Class<T> getDomainClass(Class<T> theClass) { // use theClass } } 
+3
source share

The only way I know:

 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 information about the runtime, it is missing from the compiler.

+3
source share

You can do this if you want a generic type that you inherit from! Add this method to your class and make a 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; } 
+1
source share

If you need to know the type, you probably shouldn't use generics.

0
source share

All Articles