1. 程式人生 > 實用技巧 >根據註解獲取物件屬性值,封裝成Map

根據註解獲取物件屬性值,封裝成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+"---------");
}