package CheShiKuangJia;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
//简单的测试框架
//当主方法执行后,会自动执行被检测的方法(加了Check注解的方法),判断方法是否有异常,记录到文件中
public class TestCheck {
public static void main(String[] args) throws IOException {
//创建测试对象
Caculator c=new Caculator();
//获取字节码文件
Class cls = Caculator.class;
//获取所有方法
Method[] methods = cls.getMethods();
int number=0;//出现异常的次数
BufferedWriter bw=new BufferedWriter(new FileWriter("anno\\src\\CheShiKuangJia\\bug.txt"));
for (Method method : methods) {
//判断方法上是否有Check注解
if (method.isAnnotationPresent(CheShiKuangJia.Check.class)){
try {
method.invoke(c);
} catch (Exception e) {
//捕获异常,纪录到文件中
number++;
bw.write(method.getName()+"方法出异常了");
bw.newLine();
bw.write("异常的名称:"+e.getCause());
bw.newLine();
bw.write("异常原因:"+e.getCause().getMessage());
bw.newLine();
bw.write("--------------------------------------------------");
bw.newLine();
}
}
}
bw.write("本次测试一共出现了"+number+"次异常");
bw.flush();
bw.close();
}
}
Check注解
package CheShiKuangJia;
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 {
}
测试类
package CheShiKuangJia;
@Check1
public class Caculator {
@Check
public void add(){
String str=null;
str.toString();
System.out.println("1+0="+(1+0));
}
@Check
public void subtract(){
System.out.println("1-0="+(1-0));
}
@Check
public void multiply(){
System.out.println("1*0="+(1*0));
}
public void divide(){
System.out.println("1/0="+(1/0));
}
}
bug.txt
add方法出异常了
异常的名称:java.lang.NullPointerException
异常原因:null
--------------------------------------------------
本次测试一共出现了1次异常