public class Calculator {
@Check
public void add(){
System.out.println(1+2);
}
@Check
public void sub(){
System.out.println(2-1);
}
@Check
public void mul(){
System.out.println(2*8);
}
@Check
public void div(){
System.out.println(1/0);
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
public class TestCheck {
public static void main(String[] args) throws IOException {
int num=0;//记录出现异常的次数
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("check.txt"));
//1.创建计算器对象
Calculator calculator = new Calculator();
//2.获取字节码对象
Class<? extends Calculator> aClass = calculator.getClass();
//3.获取所有方法
Method[] declaredMethods = aClass.getDeclaredMethods();
//4.判断方法上是否有Check注解
for (Method method:declaredMethods){
if (method.isAnnotationPresent(Check.class)){
try {
//5.执行
method.invoke(calculator);
}catch (Exception exception){
//6.捕获异常,记录到文件中
num++;
bufferedWriter.write(method.getName()+"方法出现异常");
bufferedWriter.newLine();
bufferedWriter.write(String.valueOf(exception.getCause().getClass().getSimpleName()));
bufferedWriter.newLine();
bufferedWriter.write(exception.getCause().getMessage());
bufferedWriter.newLine();
bufferedWriter.write("______________________________");
}
}
}
bufferedWriter.write("本次测试一共出现"+num+"次异常");
bufferedWriter.flush();
bufferedWriter.close();
}
}
网友评论