Claculator类中:
public class Calculator {
@Check
public void add() {
String str = null;
str.toString();
System.out.println("1+2=" + (1 + 0));
}
@Check
public void sub() {
System.out.println("1+2=" + (1 - 0));
}
@Check
public void mul() {
System.out.println("1+2=" + (1 * 0));
}
@Check
public void div() {
System.out.println("1+2=" + (1 / 0));
}
public void show() {
}
}
Check注解中
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}
测试类中:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
/*
简单的测试框架
当主方法执行后,会自动执行被检测的所有方法(加了Check注解的方法),判断方法是否有异常,记录到文件中
* */
public class TestCheck {
public static void main(String[] args) throws IOException {
//创建计算器对象
Calculator c = new Calculator();
// 获取字节码文件
Class cls = c.getClass();
// 获取所有方法
Method[] methods = cls.getMethods();
int num = 0;//出现异常的次数
BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
for (Method method : methods) {
//判断方法上是否有Check注解
if (method.isAnnotationPresent(Check.class)) {
try {
//有,执行
//在框架中经常会会用到method.invoke()方法,用来执行某个的对象的目标方法。
method.invoke(c);
} catch (Exception e) {
//e.printStackTrace();
num++;
bw.write(method.getName() + "方法出异常了");
bw.newLine();
bw.write("异常名称:" + e.getCause().getClass().getSimpleName());
bw.newLine();
bw.write("异常的原因:" + e.getCause().getMessage());
bw.newLine();
bw.write("--------");
bw.newLine();
}
}
}
bw.write("本次测试一共出现" + num + "次异常");
bw.flush();
bw.close();
}
}
运行时:
生成的bug.txt中