public class TestableExceptionProcessor {
public static void process(String clazz) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
int passed = 0;
int failed = 0;
Object obj = Class.forName(clazz).newInstance();
for (Method method : Class.forName(clazz).getMethods()) {
if (method.isAnnotationPresent(TestableException.class)) {
try {
method.invoke(obj, null);
// 没有抛出异常(失败)
++failed;
} catch (InvocationTargetException e) {
// 获取异常的引发原因
Throwable cause = e.getCause();
int oldPassed = passed;
for (Class excType : method.getAnnotation(TestableException.class).value()) {
// 是我们期望的异常类型之一(成功)
if (excType.isInstance(cause)) {
++passed;
break;
}
}
// 并不是我们期望的异常类型(失败)
if (oldPassed == passed) {
++failed;
System.out.printf("Test <%s> failed <%s> %n", method, e);
}
}
}