使用注解:
1、获取注解定义的位置对象 (Class,Method,Field)
2、获取指定的注解 getAnnotation(Class)
3、调用注解中的抽象方法
自定义Check注解:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}
Calculator类中只有method方法没有加@Check注解:
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));
}
public void method(){
System.out.println("我是method方法.....");
}
}
main测试:
public class MyAnnotationTest {
public static void main(String[] args) {
Calculator calculator = new Calculator();
//获取Calculator字节码文件对象
Class<? extends Calculator> aClass = calculator.getClass();
//获取文件中所有方法
Method[] methods = aClass.getMethods();
for (Method method : methods) {
//如果方法上有@Check注解,则执行该方法
if (method.isAnnotationPresent(Check.class)) {
try {
method.invoke(calculator);
} catch (Exception e) {
System.out.println("出现异常的方法名:" + method.getName());
System.out.println("异常出现的原因:" + e.getCause().getMessage());
}
}
}
}
}
控制台信息: