1、注解类
package com.springboot.annotationTest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by xp on 2020-12-08.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface check {}
2、普通方法类
package com.springboot.annotationTest;
/**
* Created by xp on 2020-12-08.
*/
public class Cal {
@check
public void add() {
System.out.println("1+2=" + (1 + 2));
}
@check
public void div() {
System.out.println("1/0=" + (1 / 0));
}
}
3、逻辑判断类
package com.springboot.annotationTest;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* Created by xp on 2020-12-08.
*/
public class test {
public static void main(String[] args) throws IOException {
Cal cal = new Cal();
Class aClass = cal.getClass();
Method[] methods = aClass.getMethods();
BufferedWriter bw = new BufferedWriter(new FileWriter("error.txt"));
int num=0;
for (Method method : methods) {
if (method.isAnnotationPresent(check.class)) {
try {
Object o = method.invoke(cal);
} catch (Exception e) {
num++;
bw.write("异常名称:"+e.getCause().getClass().getSimpleName());
bw.write("{}方法异常"+method.getName());
e.printStackTrace();
}
}
}
bw.write("异常次数:"+num);
bw.flush();
bw.close();
}
}
##逻辑判断部分的代码可以通过切面的方式进行改造