将java.lang.reflect.Type转换为Class< T>爵士乐

将java.lang.reflect.Type转换为Class< T>爵士乐

问题描述:

如何将java.lang.reflect.Type转换为Class<T> clazz?

如果下一个方法的参数为Class<T>:

If I have one method as next which has an argument of Class<T>:

public void oneMethod(Class<T> clazz) {     
    //Impl
}

然后是另一个方法,该方法的参数为java.lang.reflect.Type,它调用oneMethod(Class<T> clazz),为此,我需要将java.lang.reflect.Type type转换为Class<T>:

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>?);
}

有可能吗?

您必须确保typeClass的实例,然后将其强制转换.

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);
}

当然,您还必须处理它不是Class的情况.

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