How can I convert java.lang.reflect.Type
to Class<T> clazz
?
If I have one method as next which has an argument of Class<T>
:
public void oneMethod(Class<T> clazz) { //Impl }
Then another method which has an argument of java.lang.reflect.Type
and it calls oneMethod(Class<T> clazz)
and for it I need to convert java.lang.reflect.Type type
to Class<T>
:
public void someMehtod(java.lang.reflect.Type type) { // I want to pass type arg to other method converted in Class<T> otherMethod(¿How to convert java.lang.reflect.Type to Class<T>?); }
Is it possible?
You have to ensure that type
is an instance of Class
, and then cast it.
if (type instanceof Class) { Class<?> clazz = (Class<?>) type; otherMethod(clazz); }
Of course, you also have to handle the case of it not being a Class
.
If you are willing to use a library, you could use com.google.guava:guava:12+
:
Class<?> clazz = com.google.common.reflect.TypeToken.of(type).getRawType();
Alternatively you could also use com.fasterxml.jackson.core:jackson-databind:2.8.x
:
Class<?> clazz = com.fasterxml.jackson.databind.type.TypeFactory.rawClass(type);
This handles all cases correctly and you will get the type-erased class of your type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With