测试一个计算器类,把异常类型次数其他异常信息自动生成BUG文件
/**
* 计算器类
*/
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...");
}
}
注解
```java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)描述注解被保留的阶段 三个阶段之一运行阶段
@Target(ElementType.METHOD)ElementType描述注解能够作用的位置 METHOD:可以作用于方法上
public @interface Check {
}
当主方法执行后,会自动自行被检测的所有方法(加了Check注解的方法),判断方法是否有异常,记录到文件中
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 number = 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.捕获异常
//记录到文件中
number ++;
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("本次测试一共出现 "+number+" 次异常");
bw.flush();
bw.close();
}
}
效果展示
运行自动生成bug.txt文件