How can I convert java.lang.reflect.Type
to Class
?
If I have one method as next which has an argument of Class
It would be weird that a Type
would be anything else than a Class
... Javadoc for Type
says
All Known Implementing Classes: Class
So unless you have special libraries that use non Class
Type
s, you can simply cast - but you must be ready for a possible ClassCastException
.
Beware: Java use undocumented Type implementation to represent generics, see below.
You can explicitely process it or not because it is an unchecked exception:
Explicit way:
try {
Class> clazz = (Class>) type;
}
catch (ClassCastException ex) {
// process exception
}
Implicit way:
Class> clazz = (Class>) type;
but the current method could throw...
EDIT per @Andy Turner's comment:
Beware: Type type = new ArrayList
yields something that's a Type but not a Class. This one is a ParameterizedType
, so you can use getRawType()
method to find the actual class, but others might exist.