案例:简单的框架测试
准备一个Calculator类,一个注解,一个测试类。
Check注解的代码为:
package top.imcyc.day07.annotation.demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)//限用于方法之上
public @interface Check {
}
Calculator类中写一些正常的方法,写一些会抛出异常的方法,以便测试类测试。类代码为:
package top.imcyc.day07.annotation.demo;
public class Calculator {
@Check
public void add() {
System.out.println("1+0 =" + (1 + 0));
}
@Check
public void sub() {
String str = null;
str.toString();//会出现空指针异常
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));//会出现数学异常
}
public void show() {
System.out.println("HelloWorld");
}
}
测试类代码为:
package top.imcyc.day07.annotation.demo;
import java.io.*;
import java.lang.reflect.Method;
public class TestCheck {
public static void main(String[] args) throws IOException {
//1.创建计算器对象
Calculator cal = new Calculator();
//2.获取字节码文件对象
Class cls = cal.getClass();
//3.获取所有方法
Method[] methods = cls.getMethods();
int num = 0;//出现异常的次数
BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
for (Method method : methods) {
if (method.isAnnotationPresent(Check.class)) {//判断方法上有没有指定的注解
try {
method.invoke(cal);
} catch (Exception e) {
//捕获异常,并记录到文件中
num++;
bw.write(method.getName() + "方法出现异常");
bw.newLine();
//bw.write("异常的名称:"+e.getCause());//java.lang.ArithmeticException: / by zero
//bw.write("异常的名称:"+e.getCause().getClass().getName());//java.lang.ArithmeticException
bw.write("异常的名称:" + e.getCause().getClass().getSimpleName());//ArithmeticException
bw.newLine();
bw.write("异常的原因:" + e.getCause().getMessage());
bw.newLine();
bw.write("------------------------------------");
bw.newLine();
}
}
}
bw.write("本次测试一共出现" + num + "次异常");
bw.flush();
bw.close();
}
}
程序执行结束后,会生成bug.txt文件,文件内容为:
当测试类执行后,会自动自行被检测的所有方法(加了Check注解的方法),判断方法是否有异常,记录到文件中。可以看到每一个异常都会被详细记录下来。
总结:
- 为什么要加注解?在类中的成员方法上加注解,主方法执行的时候才能分辨出哪些方法是需要检查的。加注解其实相当于贴“标签”,让主程序来分辨。
- 大多数时候,我们会使用注解,而不是自定义注解。