注解
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
public @interface check {
}
被测试类
public class Main {
@check
public void add() {
System.out.println("1+0=" + 1 + 0);
}
@check
public void div1() {
System.out.println("1/0=" + 1 / 0);
}
@check
public void div2() {
System.out.println("1/0=" + 1 / 0);
}
}
测试方法
public class MainTest {
public static void main(String[] args) throws IOException {
//创建对象
Main main = new Main();
//获得字节码对象
Class clazz = main.getClass();
//获得方法
Method[] arr = clazz.getMethods();
//记录Bug数
int num = 0;
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("bug.txt"));
/**
* 测试得到的方法
*/
for (Method m : arr
) {
//判断方法上是否有注解
if (m.isAnnotationPresent(check.class)) {
//有执行
try {
m.invoke(main);
} catch (Exception e) {
//捕获异常
num++;
//记录到文件中
bufferedWriter.write(m.getName() + "出异常了");
bufferedWriter.newLine();
bufferedWriter.write("名称" + e.getCause().getClass().getSimpleName());
bufferedWriter.newLine();
bufferedWriter.write("原因" + e.getCause().getMessage());
bufferedWriter.newLine();
bufferedWriter.write("---------");
bufferedWriter.newLine();
}
}
}
bufferedWriter.write("本次共" + num + "个bug");
//关流
bufferedWriter.close();
}
}
显示效果
div1出异常了
名称ArithmeticException
原因/ by zero
---------
div2出异常了
名称ArithmeticException
原因/ by zero
---------
本次共2个bug
注解知识