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

      

  • 相关阅读:
    最好的 6 个 HTML5 的多媒体播放器
    原型开发、模型构建和设计反馈在线工具
    让Xcode 4.2生成的app支持旧版iOS设备(armv6)
    TOUCHXML解析xml
    50 个最佳 CSS3 教程大放送
    十八般武艺!移动应用开发者必备的18款利器
    ios开源程序集
    iOS如何隐藏各种bar
    读书笔记之:C语言教程(C程序设计第三版)——清华大学
    JM8.6中帧内帧间模式的选择
  • 原文地址:https://www.cnblogs.com/notably/p/13410056.html
Copyright © 2011-2022 走看看