1、创建注解
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 {
}
2、创建类
/**
* @author liupeng
* @date 2022-03-11 9:56
*/
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("永无bug...");
}
}
3、测试类
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* @author liupeng
* @date 2022-03-11 9:56
*/
public class TestCheck {
public static void main(String[] args) throws IOException {
Calculator calculator = new Calculator();
//获取计算器字节码文件对象
Class<? extends Calculator> aClass = calculator.getClass();
//记录bug出现次数
int number = 0;
BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
//获取所有的方法
for (Method method : aClass.getMethods()) {
if (method.isAnnotationPresent(Check.class)) {
try {
method.invoke(calculator);
} catch (Exception e) {
//捕获异常 记录在文件中
number++;
bw.write(method.getName() + "方法出异常");
bw.newLine();
bw.write("异常的名称:" + e.getCause().getClass().getSimpleName());
bw.newLine();
bw.write("异常的原因:" + e.getCause().getMessage());
bw.newLine();
}
}
}
bw.write("本次测试一共出现了:" + number + "次异常");
bw.flush();
if (bw != null) {
bw.close();
}
}
}