反射中,Method.getParameterAnnotations()用法

6 篇文章 0 订阅
1 篇文章 0 订阅

Method.getParameterAnnotations()用法

最近学习反射和注解,顺便记录下来

定义@MyRequestParameter注解

@Target(value = {ElementType.PARAMETER}) //表示该注解只能应用在参数上
@Retention(value = RetentionPolicy.RUNTIME) //表示该注解在运行时期仍可以起作用
public @interface MyRequestParameter {
    String value() default "";
}

定义@MyRequestParameter1注解

@Target(value = {ElementType.PARAMETER}) //表示该注解只能应用在参数上
@Retention(value = RetentionPolicy.RUNTIME) //表示该注解在运行时期仍可以起作用
public @interface MyRequestParameter1 {
    String value() default "";
}

添加测试方法

    public void testParameterAnnotations(@MyRequestParameter("name") @MyRequestParameter1("name1") String name,
                                         @MyRequestParameter("telephone") String telephone,Integer age){

    }

测试

    public static void main(String[] args) throws NoSuchMethodException {
        Class<Test> clazz = Test.class;
        Method method=clazz.getMethod("testParameterAnnotations", String.class, String.class,Integer.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  MyRequestParameter){
                    MyRequestParameter myRequestParameter=(MyRequestParameter) annotations[i][j];
                    System.out.println("annotations["+i+"]["+j+"] = " + myRequestParameter.value());
                }else if(annotations[i][j] instanceof  MyRequestParameter1){
                    MyRequestParameter1 myRequestParameter1=(MyRequestParameter1) annotations[i][j];
                    System.out.println("annotations["+i+"]["+j+"] = " + myRequestParameter1.value());
                }
            }
        }
    }

输出

1个参数有2个注解
annotations[0][0] = name
annotations[0][1] = name1
第2个参数有1个注解
annotations[1][0] = telephone
第3个参数有0个注解

总结

在这里解释一下,

Annotation[][] annotations = method.getParameterAnnotations();

为什么返回的是一个二维数组呢,这是因为每一个参数前面可能会有多个不同注解修饰。其中annotations[0]代表第一个参数,annotations[1]代表第二个参数。
像第一个参数的话,它有2个注解,annotations[0][0]表示第一个注解,annotations[0][1]表示第二个注解,
第二个参数的话,它只有1个注解,因此用annotations[1][0]表示这个注解
由于第三个参数上没有注解,所以就没有数据。
有什么理解错误的话,欢迎大家各位指正!

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值