参考: spring注解工具类AnnotatedElementUtils和AnnotationUtils
Spring 注解编程模型
ReflectUtils
//获取指定类type上的方法methodName
findDeclaredMethod(Class type, String methodName, Class[] parameterTypes)
AnnotationUtils
getAnnotation: 从某个类获取某个annotation。(一级元注解查找)
findAnnotation: 从类或方法中查找某个annotation。(多级元注解递归查找)
isAnnotationDeclaredLocally: 验证annotation是否直接注释在类上而不是集成来的。
isAnnotationInherited: 验证annotation是否继承于另一个class。
getAnnotationAttributes: 获取annotation的所有属性。
getValue: 获取指定annotation的值.
getDefaultValue: 获取指定annotation或annotation 属性的默认值
@RequestMapping("/test")
public class AnnoTest {
@Test
@RequestMapping(value = "/GetMapping", method = RequestMethod.GET)
public void annotationUtilsTests () throws Exception{
//获取AnnoTest类中annotationUtilsTests方法上的RequestMapping注解
Method method = ReflectUtils.findDeclaredMethod(AnnoTest.class, "annotationUtilsTests", null);
RequestMapping requestMappingAnno = AnnotationUtils.getAnnotation(method, RequestMapping.class);
System.out.println(Lists.list(requestMappingAnno.value())); //[/GetMapping]
System.out.println(Lists.list(requestMappingAnno.method())); //[GET]
//查找AnnoTest类上的RequestMapping注解
RequestMapping annotation = AnnotationUtils.findAnnotation(AnnoTest.class, RequestMapping.class);
System.out.println(Lists.list(annotation.value())); //[/test]
}
}
AnnotatedElementUtils
下面所有变体都支持组合注解中带有属性覆盖的元注解的方法
get* (一级元注解查找)
find* (多级元注解递归查找)
getMergedAnnotationAttributes()
getMergedAnnotation()
getAllMergedAnnotations()
getMergedRepeatableAnnotations()
findMergedAnnotationAttributes()
findMergedAnnotation()
findAllMergedAnnotations()
findMergedRepeatableAnnotations()
@Test
@GetMapping(value="/reover")
public void annotatedElementUtilsTests () throws Exception{
Method method = ReflectUtils.findDeclaredMethod(AnnoTest.class, "annotatedElementUtilsTests", null);
//不支持注解属性值覆盖
RequestMapping requestMappingAnno1 = AnnotationUtils.findAnnotation(method, RequestMapping.class);
System.out.println(Lists.list(requestMappingAnno1.value())); //[]
//支持注解属性值覆盖
RequestMapping requestMappingAnno2 = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
System.out.println(Lists.list(requestMappingAnno2.value()));//[/test]
}
isInstance
判断某个对象是否是属于某个类
System.out.println(AnnoTest.class.isInstance(new AnnoTest()));//true
isAssignableFrom.
判断后者类是否属于前者类
System.out.println(AnnoTest.class.isAssignableFrom(AnnoTest.class));//true