package cn.itcast.annotation.demo;import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** 简单的测试框架** 当主方法执行后,会自动执行被检测方法 加了check注解,判断方法是否有异常,记录到文件中*/
public class TestCheck {public static void main(String[] args) throws IOException {// 1.创建对象Calculator c = new Calculator();// 2.获取字节码文件对象Class<? extends Calculator> cls = c.getClass();// 3.获取所有方法Method[] methods = cls.getMethods();int number = 0; // 出现异常的次数BufferedWriter bw = new BufferedWriter(new FileWriter("..\\basis\\bug.txt"));for (Method method : methods){// 4.判断方法是否有Check注释if(method.isAnnotationPresent(Check.class)){try {// 5.执行method.invoke(c);} catch (Exception e) {// 6. 捕获异常// e.printStackTrace();number++;long l = System.currentTimeMillis();bw.write(Long.toString(l));bw.newLine();bw.write(method.getName()+"方法出异常了");bw.newLine();bw.write("异常的名称:"+e.getCause().getClass().getSimpleName());bw.newLine();bw.write("异常的原因:"+e.getCause().getMessage());bw.write("-----------------");bw.newLine();}}}bw.write("本次测试一共出现"+number+"次异常!");bw.flush();bw.close();}
}
package cn.itcast.annotation.demo;public class Calculator {@Checkpublic void add(){System.out.println("1 + 0 =" + (1 + 0));}@Checkpublic void mul(){System.out.println("1 / 0 =" + (1 / 0));}@Checkpublic void div(){System.out.println("1 * 0 =" + (1 * 0));}public void show(){System.out.println("水水水");}
}
package cn.itcast.annotation.demo;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 {
}