java反射 - 解析注解

掌握了 Java 反射技能,一般不会有太多问题,需要特殊注意的是:注解中的字段其实不是 Field,而是 Method。

以下面这个注解为例,value 不是 Field,而是 Method。

@Inherited
@Target({ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@interface Example {

    // 普通字段
    String value() default "";
}

代码样例


package com.jeeplus.config;

import javax.validation.constraints.Size;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author Mr.css
 * @version 2022-10-08 9:51
 */
public class Test {

    @Size(groups = {Test.class})
    private String name;

    public static void main(String[] args) throws NoSuchFieldException
            , NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<?> clazz = Test.class;

        // 遍历 name 字段上的注解
        Field field = clazz.getDeclaredField("name");
        Annotation[] annotations = field.getAnnotations();
        // 因为只有 1 个注解,所以读到的必定是 @Size
        for (Annotation annotation: annotations){
            Class<?> cla = annotation.annotationType();
            // 注解的字段,看起来是 field,实际上是 method,需要通过 invoke() 获取属性值
            Method method = cla.getDeclaredMethod("groups");
            Class<?>[] groups = (Class<?>[]) method.invoke(annotation);
            System.out.println(Arrays.toString(groups));
        }
    }
}

posted on 2022-10-13 12:00  疯狂的妞妞  阅读(37)  评论(0编辑  收藏  举报

导航