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;
}

你可能感兴趣的:(java基础)