Java 通过反射获取定义在方法参数上的注解

先来看一段 Spring MVC 经常用到的定义在方法参数上的注解:

@RestController
@RequestMapping("/param")
public class ParamTestController {
    @PostMapping("/upload")
    public void upload(@RequestParam("userId") long userId, @RequestParam(value = "file", required = false) MultipartFile file) {
        System.out.println(Objects.isNull(file));
    }
}

比如我们常用的注解 @RequestParams,是定义在方法参数上的,那是怎么通过 Java 获取方法参数上的注解信息呢?参数前可以添加多个注解,一个参数上不能添加多个相同的注解,相同的注解可以添加到不同的参数上。

下面有这样一个类,现在需要获取到参数上的注解信息。

public class SkyService {

    public String blue(int color,
                       @CustomAnnotation(value = "one")
                       @CustomAnnotation1(value = "two")
                       @CustomAnnotation2(value = "three") String big,
                       @CustomAnnotation1("four") @CustomAnnotation2("five") String bala) {
        return "What blue sky it is";
    }
}

来看代码:

        @Test
    public void testParamAnnotation() {
        // 获取方法的反射对象
        Method[] methods = SkyService.class.getMethods();
        Class<?>[] parameterTypes = methods[0].getParameterTypes();
        Annotation[][] pa = methods[0].getParameterAnnotations();
        // 二维数组遍历,第一维是参数的个数,第二维是具体的注解值
        for (int i = 0; i < parameterTypes.length; i++) {
            // 每个参数对应的注解数组
            for (Annotation annotation : pa[i]) {
                if (annotation instanceof CustomAnnotation) {
                    System.out.println(((CustomAnnotation) annotation).value());
                } else if (annotation instanceof CustomAnnotation1) {
                    System.out.println(((CustomAnnotation1) annotation).value());
                } else if (annotation instanceof CustomAnnotation2) {
                    System.out.println(((CustomAnnotation2) annotation).value());
                }
            }
        }
    }

在这里插入图片描述
从上图的断点中可以看出,Annotation[][] pa = methods[0].getParameterAnnotations();得到的是一个二维数组,第一维是参数的个数,第二维是注解数组,也就是说第一个参数的下标为 0,第二个参数的下标为 1,以此类推。如果某个参数没有注解标注得到的就是一个长度为 0 的数组,比如 SkyService.blue 方法中的有三个参数,第一个 color 参数是没有注解标注的,可以看到 pa[0] 对应的数组长度是 0。然后 pa[1] 表示第二个参数有三个注解,pa[2] 表示第三个参数有两个注解。

😆,你就说神不神奇。

参考:java.lang.reflect.Method.getParameterAnnotations()方法示例

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值