Get Generic Exception Types in Java
Description
The following code shows how to get Generic Exception Types.
Example
import static java.lang.System.out;
// w w w.j a v a 2s. c om
import java.lang.reflect.Method;
import java.lang.reflect.Type;
public class Main {
public static void main(String... args) throws Exception {
String fmt = "%24s: %s%n";
Class<?> c = MethodSpy.class;
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
if (!m.getName().equals(args[1])) {
continue;
}
out.format("%s%n", m.toGenericString());
Class<?>[] xType = m.getExceptionTypes();
Type[] gxType = m.getGenericExceptionTypes();
for (int i = 0; i < xType.length; i++) {
out.format(fmt, "ExceptionType", xType[i]);
out.format(fmt, "GenericExceptionType", gxType[i]);
}
}
}
}
class MethodSpy {
// for the morbidly curious
<E extends RuntimeException> void genericThrow() throws E {
}
}