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
getGenericReturnTypewill always be aParameterizedType. Sometimes it will just be aClassif the return type isn’t generic. See this example for how to achieve what you need usinginstanceof:Note that
getGenericReturnTypemay return more possible subinterfaces ofTypewhich you will need to account for somehow, either by handling them also or throwing a runtime exception.See this article for more information/examples.