根据注解获取对象属性值,封装成Map

创建两个注解,一个类上的注解、一个属性上的主键。

  类上的注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TheType {
    String name() default "默认值";
}

  属性上的注解

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TheValue {
    String object() default "default value";
}

  获取属性值返回Map

class GetObjectValueUtil {
    static <T> Map getAnnotationVal(T t){
        System.out.println(t.getClass());
        Map<String,Object>resultMap=new HashMap<>();
        if(null!=t.getClass().getAnnotation(TheType.class)){
            Field[] declaredFields = t.getClass().getDeclaredFields();
            for (Field f:declaredFields) {
                TheValue value = f.getAnnotation(TheValue.class);
                if(null!=value){
                    String defaultValue = value.object();
                    String fieldName=f.getName();
                    String methodName="get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                    Object invoke=null;
                    try {
                        System.out.println("---------methodName="+methodName);
                         invoke = t.getClass().getMethod(methodName).invoke(t)==null?defaultValue:t.getClass().getMethod(methodName).invoke(t);
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                    resultMap.put(fieldName,invoke);
                }
            }
        }
        return resultMap;
    }
}

  测试类:

@Data
@TheType
@AllArgsConstructor
@NoArgsConstructor
public class BaseDataDto {
    @TheValue
    private String name;
    @TheValue
    private Integer age;
    @TheValue
    private FatheCla cla;
    private String ignore;
}

  

 public static void main(String[] args) {

        BaseDataDto dto=new  BaseDataDto();
        dto.setCla(new FatheCla("2","2","2"));
        dto.setName("dabai");
        dto.setAge(99);
        Map enumVal = GetObjectValueUtil.getAnnotationVal(dto);
        System.out.println(enumVal+"---------");
}

  

原文地址:https://www.cnblogs.com/notably/p/13410056.html