Java reflection for generics
generics, java, reflection
Solution
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.
Problem
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!