Method.getParameterAnnotations()解释,测试用例,使用场景

本文详细介绍了Java中Method.getParameterAnnotations()方法的返回值解释,通过代码示例展示了如何获取方法参数上的注解。在ZQRequestParam和ZQValid这两个自定义注解的场景下,演示了如何读取注解的值。该方法常用于MVC环境中,解析前端传入的参数注解,建立形参位置与注解映射。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

返回值解释

Method.getParameterAnnotations()各个维度理解:
返回值:annotations
返回值类型:Annotation[][]
返回值:annotations:
位置:annotations[i][j],第i个参数,第j个注解,整体表示一个注解类型
图示:
在这里插入图片描述

代码演示

ZQRequestParam

import java.lang.annotation.*;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ZQRequestParam {
    String value() default "";
}

ZQValid

@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface ZQValid {
    String value() default "";
}

DemoServiceImpl

public class DemoServiceImpl {
    public void testGetParameterAnnotations(@ZQRequestParam("name") @ZQValid("name1") String name,
                                            @ZQRequestParam("age") int age,
                                            @ZQRequestParam("telphone") String telphone){

    }
}

Test

public class Test {
    public static void main(String[] args) throws NoSuchMethodException {
        Class<DemoServiceImpl> clazz = DemoServiceImpl.class;
        Method method = clazz.getMethod("testGetParameterAnnotations", String.class, int.class, String.class);
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println("我是第" + (i + 1) + "个参数,共有" + annotations[i].length + "个注解");
            for (int j = 0; j < annotations[i].length; j++) {
                if (annotations[i][j] instanceof ZQRequestParam) {
                    System.out.println("第" + (i + 1) + "参数,第" + (j + 1) + "个注解,ZQRequestParam.value=" + ((ZQRequestParam) annotations[i][j]).value());
                } else if (annotations[i][j] instanceof ZQValid) {
                    System.out.println("第" + (i + 1) + "参数,第" + (j + 1) + "个注解,ZQValid.value=" + ((ZQValid) annotations[i][j]).value());
                }

            }
        }
    }
}

输出结果

结果截图

使用场景

用于访问MVC前端通过HTTPS访问后端,获得形参参数位置-参数注解位置的注解,并整理出访问方法的形参位置与形参名称name(如@RequestParam(value=“name”))做映射关系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员入门中

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值