被检测的类,Calculator类:
public class Calculator {
@Check
public void add(){
System.out.println("1 + 0 = " + (1+0));
}
@Check
public void sub(){
System.out.println("1 - 0 = " + (1-0));
}
@Check
public void mul(){
System.out.println("1 * 0 = " + (1*0));
}
@Check
public void div(){
System.out.println("1 / 0 = " + (1/0));
}
public void show(){
System.out.println("no bug......");
}
}
Check.java
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 {
}
TestCheck.java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
public class TestCheck {
public static void main(String[] args) throws IOException {
//1、创建计算器对象
Calculator c = new Calculator();
//2、获取字节码文件对象
Class cls = c.getClass();
//3、获取所有方法
Method[] methods = cls.getMethods();
int count = 0; //出现异常的次数
BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
for (Method method : methods) {
//4、判断方法是否有Check注释
if(method.isAnnotationPresent(Check.class)){
//5、有注释,执行
try {
method.invoke(c);
} catch (Exception e) {
//6、捕获异常,记录到文件中
count++;
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("本次测试一共出现了 " + count + " 次异常");
bw.flush();
bw.close();
}
}
执行结果以及异常记录文件: