Java 自定义注解,反射获取注解的值

自定义注解

import java.lang.annotation.*;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ParamDesc {
    //描述
    String desc() default "";
    //默认值
    String def() default "";
}

通过field.getAnnotation(ParamDesc.class); 获取注解对象

/**
* 获取常量参数数据
* @param pattern 字段名称
* @return
* @throws IllegalAccessException
*/
public static List<Map<String, String>> generator(String pattern) throws IllegalAccessException {
   //PmsParamConfigConstant.class 注解在字段的类
   Field[] fields = PmsParamConfigConstant.class.getDeclaredFields();
   List<Map<String, String>> list = new ArrayList<>();
   for (Field field : fields) {
       if (Pattern.matches(pattern, field.getName())) {
           field.setAccessible(true);
           String code = (String) field.get(PmsParamConfigConstant.class);
           String desc = null;
           String def = null;
           ParamDesc annotation = field.getAnnotation(ParamDesc.class);
           if (annotation != null) {
               desc = annotation.desc().equals("") ? null : annotation.desc();
               def = annotation.def().equals("") ? null : annotation.def();
           }
           Map<String, String> map = new HashMap<>();
           map.put("code", code);
           map.put("desc", desc);
           map.put("def", def);
           list.add(map);
       }
   }
   return list;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值