Get Generic Return Type in Java
Description
The following code shows how to get Generic Return Type.
Example
/* ww w .jav a 2 s . c om*/
import static java.lang.System.out;
import java.lang.reflect.Method;
public class Main {
public static void main(String... args) {
try {
String fmt = "%24s: %s%n";
Class<?> c = Class.forName(args[0]);
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
if (!m.getName().equals(args[1])) {
continue;
}
out.format("%s%n", m.toGenericString());
out.format(fmt, "ReturnType", m.getReturnType());
out.format(fmt, "GenericReturnType", m.getGenericReturnType());
}
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
}
}
}
class MethodSpy {
// for the morbidly curious
<E extends RuntimeException> void genericThrow() throws E {
}
}