Java Reflect - 利用反射获取方法参数上的注解

1. AnnotatedElement接口

AnnotatedElement接口表示目前正在此 JVM 中运行的程序的一个已注释元素,该接口允许反射性地读取注释。

调用AnnotatedElement对象的如下方法可以访问Annotation信息:

  • getAnnotation(Class<T>annotationClass):返回该程序元素上存在的指定类型的注释,如果该类型的注释不存在,则返回null。
  • Annotation[] getAnnotations():返回此元素上存在的所有注释。
  • boolean isAnnotationPresent(Class<?extendsAnnotation>annotationClass):判断该程序元素上是否存在指定类型的注释,如果存在则返回true,否则返回false。
  • Annotation[] getDeclaredAnnotations():返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。

2. Method类实现了AnnotatedElement接口

相对于AnnotatedElement接口新增的方法:获取方法参数上的注解

getParameterAnnotations :返回表示按照声明顺序对此 Method 对象所表示方法的形参进行注释的那个数组的数组

public Annotation[][] getParameterAnnotations();

3. 获取方法参数上的注解

① 自定义注解

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD,ElementType.PARAMETER} )
public @interface MyParam1 {

    String value() default "";
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD,ElementType.PARAMETER} )
public @interface MyParam2 {

    String value() default "";
}

② 给方法参数上添加注解

public class Test {
    
    public void show1(
            @MyParam1("name1") @MyParam2("name2") String name,
            @RequestParam("email") String email,
            @MyParam1("phone") String phone){
        System.out.println("111");
    }

    public void show2(@RequestParam("email") String email){
        System.out.println("111");
    }
}

③ 获取show1()方法参数上的注解

public class Main {
    public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException {

        // 得到Class类对象
        Class<?> clazz = Class.forName("com.example.redislock.annotation.Test");

        // 获取Test类的所有方法
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            // 方法上可能有多个参数,每个参数上可能有多个注解,所以是二维数组
            // annotations[0][0]表示第1个参数的第1个注解
            // annotations[0][1]表示第1个参数的第2个注解
            Annotation[][] annotations = method.getParameterAnnotations();
            for(int i=0;i<annotations.length;i++){
                for(int j= 0;j<annotations[i].length;j++){
                    if(annotations[i][j] instanceof MyParam1){
                        MyParam1 myParam1 = (MyParam1) annotations[i][j];
                        System.out.println(myParam1);
                    }
                }
            }
        }
    }
}

在这里插入图片描述

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我一直在流浪

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

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

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

打赏作者

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

抵扣说明:

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

余额充值