注解
@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
注解知识
![1716035-20190721140152402-75428070.png](https://i-blog.csdnimg.cn/blog_migrate/8a758ea049b976c3cb440fe92d326067.png)
![1716035-20190721140207603-151792675.png](https://i-blog.csdnimg.cn/blog_migrate/c97c9bb52f9636f4f0322cc064611f1a.png)
![1716035-20190721140211689-250087609.png](https://i-blog.csdnimg.cn/blog_migrate/d1e232d1fa91c01eca398c69bb145ddb.png)
![1716035-20190721140215832-1511454491.png](https://i-blog.csdnimg.cn/blog_migrate/f981a96144dea65e2b72858d30cafc9c.png)
![1716035-20190721140219882-715587220.png](https://i-blog.csdnimg.cn/blog_migrate/6fee3a4dd8e70f53948d609dcf16a42b.png)
![1716035-20190721140223564-724086766.png](https://i-blog.csdnimg.cn/blog_migrate/1a6af41abf1fbe19714bbd1922277e63.png)
![1716035-20190721141034201-1748517174.png](https://i-blog.csdnimg.cn/blog_migrate/3a99a02563a0676c9cf92f8a3be963a8.png)