注解框架测试案例

Calculator类文件

public class Calculator {
    @Chack
    public static void add(){
        System.out.println("1 + 0 = " + (1 + 0));
    }
    @Chack
    public static void sub(){
        System.out.println("1 - 0 =" + (1 - 0));
    }
    @Chack
    public static void mul(){
        System.out.println("1 + 0 =" + (1 * 0));
    }
    @Chack
    public static void div(){
        System.out.println("1 + 0 =" + (1 / 0));
    }

}

实现测试

/
public class DemoMain {
    public static void main(String[] args) throws IOException {
        //创建Calculator类对象来获取字节码文件对象,然后获取方法对象
        Calculator c = new Calculator();
        Class cls = c.getClass();
        Method[] methods = cls.getMethods();
        //错误出现次数
        int number = 0;
        //用缓冲字符流将方法错误写入bug.txt文件中
        BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
        //遍历每个Calculator的方法
        for (Method method : methods) {
            if(method.isAnnotationPresent(Chack.class)){
                try {
                    method.invoke(c);
                } catch (Exception e) {
                    //错误写入bug.txt文件
                    bw.write(method.getName() + "方法异常");
                    bw.newLine();
                    bw.write("异常名称:" + e.getCause().getClass().getSimpleName());
                    bw.newLine();
                    bw.write("异常原因:" + e.getCause());
                    bw.newLine();
                    bw.write("-------------------");
                    bw.newLine();
                    number++;
                }
            }
        }
        bw.write("本次执行有" + number + "次异常");
        bw.close();

    }
}

Check注解文件

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Chack {
}

你可能感兴趣的:(注解框架测试案例)