/* * 注解类 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Demo04Check { }
/**要执行的小明定义的计算器类 * @author :cza * @date :2020/3/10 16:56 * @description : * @modyified By: */ public class Demo04Calculator { //加法 @Demo04Check public void add(){ System.out.println("1 + 0 = "+(1+0)); } //减法 @Demo04Check public void sub(){ System.out.println("1 - 0 = "+(1 - 0)); } //乘法 @Demo04Check public void mul(){ System.out.println("1 * 0 = "+(1 * 0)); } //除法 @Demo04Check public void div(){ System.out.println("1 /0 = "+(1/ 0)); } @Demo04Check public void show(){ System.out.println("永无bug..."); } }
/** * 简单的测试框架 * 当主方法执行后,会自动自行被检测的所有方法(加上Demo04Check注解的方法),判断方法是否有异常,记录到文件中 * @author :cza * @date :2020/3/10 17:00 * @description : * @modyified By: */ public class Demo4TestCheck { public static void main(String[] args) throws IOException { //1、创建计算器对象 Demo04Calculator c=new Demo04Calculator(); //2.获取字节码文件对象 Class cls = c.getClass(); //3.获取所有方法 Method[] methods=cls.getMethods(); int number=0; //出现异常的次数 BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("check04bug.txt")); for (Method method: methods ) { //4.判断方法上是否有Check注解 if(method.isAnnotationPresent(Demo04Check.class)){ //5、有执行 try { method.invoke(c); } catch (Exception e) { //6.捕获异常 number++; bufferedWriter.write(method.getName()+"方法出现异常了"); bufferedWriter.newLine(); bufferedWriter.write("异常的名称:"+e.getCause().getClass().getSimpleName()); bufferedWriter.newLine(); bufferedWriter.write("异常的原因:"+e.getCause().getMessage()); bufferedWriter.newLine(); bufferedWriter.write("------------------------------"); bufferedWriter.newLine(); } } } bufferedWriter.write("本次测试一共出现"+number+"次异常"); bufferedWriter.flush(); bufferedWriter.close(); } }