MST

星途 面试题库

面试题:Java反射中注解在方法参数上的处理

假设有一个方法,其参数上定义了自定义注解,在Java反射机制下,如何获取这些方法参数上的注解,并根据注解信息进行特定的业务逻辑处理?请阐述实现思路并给出关键代码片段。
39.3万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 获取目标方法对应的 Method 对象。
  2. 使用 Method 对象的 getParameterAnnotations 方法获取方法参数上的所有注解数组。
  3. 遍历注解数组,根据注解类型进行特定业务逻辑处理。

关键代码片段

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());
                    // 进行特定业务逻辑处理
                }
            }
        }
    }
}