How can I convert java.lang.reflect.Type
to Class
?
If I have one method as next which has an argument of Class
Using generic types in runtime is a little bit tricky in Java. And I think this is a root cause of your issue.
1) to be sure about generic in runtime we doing like this:
class MyClass {}
and then:
MyClass genericAwaredMyClassInctance = new MyClass(){};
please pay attention to {} in the end. It means anonymous extends of MyClass. This is an important nuance.
2) let`s improve MyClass to be able to extract the type in runtime.
class MyClass {
@SuppressWarnings("unchecked")
protected Class getGenericClass() throws ClassNotFoundException {
Type mySuperclass = getClass().getGenericSuperclass();
Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
String className = tType.getTypeName();
return (Class) Class.forName(className);
}
}
and finally, use it like this:
MyClass genericAwaredMyClassInctance = new MyClass(){};
assert(genericAwaredMyClassInctance.getGenericClass() == TargetType.class)