java中属性不一致时,如何拷贝对象

1、定义注解


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


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

2、编写工具类


import java.lang.reflect.Field;
import java.util.*;

public class FieldCopyUtil {
    public static <T,P> void copy(T source , P target) throws NoSuchFieldException, IllegalAccessException {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();
        List<Field> sourceFields = new ArrayList<>();
        List<Field> targetFields = new ArrayList<>();
        getFields(sourceClass,sourceFields);
        getFields(targetClass,targetFields);
        Map<String,Object> targetMap = getMap(targetFields,target);
        Map<String,Object> sourceMap = getMap(sourceFields,source);
        Map<String, ? extends Class<?>> sourceFileMap = sourceFields.stream().collect(Collectors.toMap(Field::getName, Field::getType));
        for(Field field : targetFields){
            field.setAccessible(true);
            FieldCopy annotation = field.getAnnotation(FieldCopy.class);
            if(annotation != null ){
                String name = annotation.name();
                if(field.getType() == sourceFileMap.get(name)){
                    field.set(target,sourceMap.get(name));
                }
            }
        }
    }

    private static Map<String, Object> getMap(List<Field> fields,Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        for (Field field :fields) {
            field.setAccessible(true);
            map.put(field.getName(),field.get(obj));
        }
        return map;
    }

    private static void getFields(Class<?> aClass, List<Field> fields) {
        // 获取子类字段
        Field[] declaredFields = aClass.getDeclaredFields();
        fields.addAll(Arrays.asList(declaredFields));
        // 取父类字段
        if (!aClass.getSuperclass().equals(Object.class)){
            getFields(aClass.getSuperclass(),fields);
        }
    }
}

3、使用
例如
类A 中的字段perName 拷贝给类B中的name,
由于字段名不一致,BeanUtils.copyProperties();不能拷贝

在类B的字段name上加上注解@FieldCopy(name="perName ")
最后掉用FieldCopyUtil.copy(A,B)

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值