zoukankan      html  css  js  c++  java
  • Bean属性复制,字段名可不同,字段类型不同需要自行处理

    @Setter
    @Getter
    public class SourceA {
    
        private String name;
        private String text;
    
        public SourceA(String name, String text) {
            this.name = name;
            this.text = text;
        }
    }
    @Setter
    @Getter
    @ToString
    public class TargetB {
    @FieldMap(name
    = "name") public LocalDateTime n; private String text; }

    注解字段名

    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface FieldMap {
        String name() default "";
    }

    实现,如果字段类型相同可以赋值,但是可能会有不同的时候。

    public static void copy(Object source, Object target) throws Exception {
            Class<?> sourceClass = source.getClass();
            Class<?> bClass = target.getClass();
    
            Field[] soutceFields = sourceClass.getDeclaredFields();
            Map<String, Object> sourceMap = new HashMap<>();
            for (Field field : soutceFields) {
                field.setAccessible(true);
                sourceMap.put(field.getName(), field.get(source));
            }
    
            Field[] targetFields = bClass.getDeclaredFields();
            for (Field field : targetFields) {
                field.setAccessible(true);
                FieldMap annotation = field.getAnnotation(FieldMap.class);
                if (annotation != null) {
                    String name = annotation.name();
                    Object sourceValue = sourceMap.get(name);
                    if (field.getType() == sourceClass.getDeclaredField(name).getType()) {
                        field.set(target, sourceValue);
                    } else {
                        /**
                         * 比如source的date字段类型为String,target接收date字段的类型为LocalDateTime
                         */
                    }
                    continue;
                }
                field.set(target, sourceMap.get(field.getName()));
            }
    
        }
  • 相关阅读:
    文件上传工具类
    使用java 的api获取两个集合的交集、并集、差集
    如何判断指定Class是否是List的子类或者父类,是否是数组
    如何判断指定Class是否是基础数据类型或者是其包装类型
    OVS中的key解析
    OVS
    Neutron网络学习
    NIO_2
    以太网帧格式总结
    VMWare中桥接、NAT、Host-only
  • 原文地址:https://www.cnblogs.com/nmnm/p/11363072.html
Copyright © 2011-2022 走看看