zoukankan      html  css  js  c++  java
  • 根据注解获取对象属性值,封装成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+"---------");
    }
    

      

  • 相关阅读:
    java中Objenesis库简单使用
    java魔法类之ReflectionFactory介绍
    求与一个数最接近的2的N次幂
    java魔法类之Unsafe介绍
    java中如何通过程序检测线程死锁
    jQuery.fullpage自定义高度(demo详解)
    angular diretive中 compile controller link的区分及编译顺序
    div水平垂直居中的几种方法(面试问题)
    angular 双ng-repeat显示隐藏
    快速应用rem
  • 原文地址:https://www.cnblogs.com/notably/p/13410056.html
Copyright © 2011-2022 走看看