通过反射获取类上的注解

背景:在一次项目开发中遇到一个需求是用@ConfigurationProperties封装配置到一个实体中,同时配置存放在apollo的配置中心里面进行统一管理。通过监听器监听对配置的修改,及时的更新封装对象中的配置属性值。这里是通过反射进行实现的,对于一个类反射获取所有的属性,跟被修改的配置值的名称进行对比,如果一直就进行更新。但是存在封装对象的属性的前缀信息在注解@ConfigurationProperties的prefix中,对比时需要前缀+属性名拼接后跟配置中心的配置名进行匹配,这就需要使用反射获取注解中的内容了。

1  //获取class对象的注解,对configurationProperties的profix获取后指定属性拼接成key
2                         ConfigurationProperties annotation = objectClass.getAnnotation(ConfigurationProperties.class);
3                         String prefix = null;
4                         if (annotation != null) {
5                             ConfigurationProperties configurationProperties = (ConfigurationProperties) annotation;
6                             prefix = configurationProperties.prefix();
7                         }
原文地址:https://www.cnblogs.com/codething/p/8663299.html