案例_@Check注解:简单的测试框架

package cn.chunzhi.Framework;

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 {
        // 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("Bug.txt"));
        for (Method method : methods) {
            // 4.判断方法上是否有Check注解
            if (method.isAnnotationPresent(Check.class)) {
                // 5.有,执行
                try {
                    method.invoke(c);
                } catch (Exception e) {
                    number ++; // 捕捉到一次异常这里就加1
                    bw.write(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 + " 次异常"); // number被写入到文件中了
        bw.close();
    }
}

被测试的计算器类:

package cn.chunzhi.Framework;

/**
 *  计算器类
 */
public class Calculator {
    @Check
    public void add() {
        String str = null;
        str.toString();
        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));
    }
}

Check注解的写法:

package cn.chunzhi.Framework;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*
    @Target:描述注解能够作用的位置
        ElementType取值:
            - TYPE:可以作用于类上
            - METHOD:可以作用于方法上
            - FIELD:可以作用于成员变量上

    @Retention:描述注解被保留的阶段
        - @Retention(RetentionPolicy.RUNTIME):当前被描述的注解,会保留到class字节码文件中,并被JVM读取到
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) // RUNTIME:运行期间
public @interface Check {
}

 异常信息:

 

 

posted @ 2020-12-06 22:37  春志  阅读(1207)  评论(0编辑  收藏  举报