Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java.lang.reflect.Type to Class<T> clazz

Tags:

java

generics

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?

like image 431
Pau Avatar asked Aug 04 '16 08:08

Pau


2 Answers

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.

like image 105
Andy Turner Avatar answered Sep 22 '22 10:09

Andy Turner


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.

like image 26
Daniel Beer Avatar answered Sep 24 '22 10:09

Daniel Beer