Convert java.lang.reflect.Type to Class & lt; T & gt; clazz

advertisements

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) {
  @SuppressWarnings("unchecked")
  Class<?> clazz = (Class<?>) type;
  otherMethod(clazz);
}

Of course, you also have to handle the case of it not being a Class.