实现思路
- 获取目标方法对应的
Method
对象。
- 使用
Method
对象的 getParameterAnnotations
方法获取方法参数上的所有注解数组。
- 遍历注解数组,根据注解类型进行特定业务逻辑处理。
关键代码片段
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
// 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@interface MyAnnotation {
String value();
}
class MyClass {
public void myMethod(@MyAnnotation("test") String param) {
// 方法体
}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Class<MyClass> myClass = MyClass.class;
Method method = myClass.getMethod("myMethod", String.class);
// 获取方法参数上的注解
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
for (Annotation annotation : parameterAnnotations[i]) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("注解值: " + myAnnotation.value());
// 进行特定业务逻辑处理
}
}
}
}
}