import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
// 定义自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String value();
}
class MyClass {
@MyAnnotation("executeLogic1")
public void myMethod() {
System.out.println("原始方法执行");
}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
MyClass myClass = new MyClass();
Method method = myClass.getClass().getMethod("myMethod");
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value();
System.out.println("注解值: " + value);
// 根据注解属性动态调整方法执行逻辑
if ("executeLogic1".equals(value)) {
System.out.println("根据注解值执行逻辑1");
} else if ("executeLogic2".equals(value)) {
System.out.println("根据注解值执行逻辑2");
}
method.invoke(myClass);
}
}
}
- 定义注解:使用
@Retention(RetentionPolicy.RUNTIME)
确保注解在运行时可用,@Target(ElementType.METHOD)
指定注解只能应用在方法上,并定义了一个属性value
。
- 定义包含注解的类和方法:
MyClass
类中的myMethod
方法应用了@MyAnnotation
注解。
- 通过反射获取注解并调整逻辑:在
main
方法中,通过反射获取myMethod
方法,检查是否存在@MyAnnotation
注解,获取注解属性值,并根据属性值动态调整逻辑,最后执行方法。