I am using Java Reflection to expose methods in custom eclipse tool.
I am writing method getReturnType
which accepts java.lang.reflect.Method
as input and returns object of Class<?>
private static Class<?> getReturnType(Method method) {
Type type = ((ParameterizedType)method.getGenericReturnType()).getRawType();
return getClass(type);
}
This code compiles well but at runtime I get the below exception while casting Type
to ParameterizedType
.
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
Please suggest. Thanks!
This doesn't work because you can't assume the result of getGenericReturnType
will always be a ParameterizedType
. Sometimes it will just be a Class
if the return type isn't generic. See this example for how to achieve what you need using instanceof
:
Type returnType = method.getGenericReturnType();
if (returnType instanceof Class<?>) {
return (Class<?>)returnType;
} else if(returnType instanceof ParameterizedType) {
return getClass(((ParameterizedType)returnType).getRawType());
}
Note that getGenericReturnType
may return more possible subinterfaces of Type
which you will need to account for somehow, either by handling them also or throwing a runtime exception.
See this article for more information/examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With