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)); } } }
标签:java,annotation,Java,groups,import,注解,解析,Class From: https://www.cnblogs.com/chenss15060100790/p/16787741.html