想被检查块
package cn.annotation.calculator;
public class Calculator {
@Check
public void add(){
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));
}
}
自定义注解
package cn.annotation.calculator;
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 {
}
package cn.annotation.calculator;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TextCheck {
public static void main(String[] args) throws IOException {
//1.创建计算器对面
Calculator c =new Calculator();
//2,获取字节码文件对象
Class cls = c.getClass();
//3,获取所有方法
Method[] methods = cls.getMethods();
int number = 0;
BufferedWriter bw= new BufferedWriter(new FileWriter("bug.txt"));
//判断方法上是否有对应注解
for (Method method : methods) {
if(method.isAnnotationPresent(Check.class)){
try {
method.invoke(c);
} catch (Exception e) {
number++;
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+"次异常");
bw.flush();
bw.close();
}
}