java BeanUtils 扩展多对象属性值复制

将源对象number类型属性的值,赋值给目标对象同类型的属性
当目标对象属性为0时 在源对象中寻找 同属性但值不为0 的属性 ,然后赋值给目标对象
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BeanUtils {

    
    public static void copyProperties(Object target, Object... sources) {
        Field[] fields = target.getClass().getDeclaredFields();
        String[] fieldNamStrings = new String[fields.length];
        for (int i = 0; i < fieldNamStrings.length; i++) {
            fieldNamStrings[i] = fields[i].getName();
        }
        for (String fieldName : fieldNamStrings) {
            try {
                Object getMethod = getGetMethod(target, fieldName);
                if (getMethod instanceof Double && (double) getMethod == 0.0D) {
                    setValue(target, fieldName, sources);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据属性,获取get方法
     *
     * @param ob   对象
     * @param name 属性名
     * @return 属性值
     * @throws Exception
     */
    private static Object getGetMethod(Object ob, String name) throws Exception {
        Method[] m = ob.getClass().getMethods();
        for (Method method : m) {
            if (("get" + name).toLowerCase().equals(method.getName().toLowerCase())) {
                return method.invoke(ob);
            }
        }
        return null;
    }

    /**
     * 根据属性,拿到set方法,并把值set到对象中
     */
    private static void setValue(Object target, String fieldName, Object... sources) {
        try {
            for (Object source : sources) {
                Object data = getGetMethod(source, fieldName);
                if (data != null && (double) data != 0) {
                    String setMethodName = "set" + fieldName;
                    Method[] methods = target.getClass().getMethods();
                    for (Method method : methods) {
                        if (setMethodName.equals(method.getName().toLowerCase())) {
                            method.invoke(target,data);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值