Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection for generics

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!

like image 895
Here to Learn. Avatar asked Feb 21 '23 21:02

Here to Learn.


1 Answers

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.

like image 130
Paul Bellora Avatar answered Feb 23 '23 11:02

Paul Bellora