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+"---------");
    }
    

      

  • 相关阅读:
    【转】CSR蓝牙驱动程序引起的Win7奇怪问题
    c# .net WebRequest 始终报域名无法解析
    sql server 安装时提示要重启
    https 不检验证书
    windows 日志,IIS应用程序池回收日志
    excel sum
    .net core 连接sql server 时提示Connection Timeout Expired
    python2.0_day20_bbs系统开发
    SVN常用命令与分支操作
    SVN使用教程之-分支/标记 合并 subeclipse
  • 原文地址:https://www.cnblogs.com/notably/p/13410056.html
Copyright © 2011-2022 走看看