注解工具类


参考: 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值