要测试的Java文件:
package com.框架测试;
/*
* @Auther: JingZ
* @Description: com.框架测试
* @version: 1.0
*/
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!!!!!!!!!!!!!!!");
}
}
注解代码(Check):
package com.框架测试;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*
* @Auther: JingZ
* @Description: com.框架测试
* @version: 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Check {
}
测试文件:
package com.框架测试;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
/*
* @Auther: JingZ
* @Description: com.框架测试
* @version: 1.0
*/
public class TestCheck {
public static void main(String[] args) throws IOException {
//创建对象
final Calculator c = new Calculator();
//获取字节码文件对象
final Class<? extends Calculator> cls = c.getClass();
//获取所有方法
final Method[] methods = cls.getMethods();
int number=0;
final BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
for (Method method : methods) {
//判断方法上是否有Check注解
if (method.isAnnotationPresent(Check.class)){
try {
method.invoke(c);
} catch (Exception e) {
//捕获异常,记录到文件中
number++;
bw.write( cls.getSimpleName()+"类中的"+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.flush();
}
}
测试结果: