java对象复制和属性值复制工具类[通俗易懂]

java对象复制和属性值复制工具类[通俗易懂]两个不同类型的对象中有字段名称不区分大小写的情况下一样,字段含义一样,需要组装到另一个对象中去,然后就写了一个这种工具类我的类型比较特殊,老系统和新系统的对象命名大小写命名不一致,并且字段相同类型也有不一致的情况,所以自己写了一个,不是很完美基本能用。温馨提示:如果同一种类型的对象属性字段名equals相等并且类型一致。则完全可以用commons-beanutils包或者spring包

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

两个不同类型的对象中有字段名称不区分大小写的情况下一样,字段含义一样,需要组装到另一个对象中去,然后就写了一个这种工具类
我的类型比较特殊,老系统和新系统的对象命名大小写命名不一致,并且字段相同类型也有不一致的情况,所以自己写了一个,
不是很完美基本能用。

温馨提示:
如果同一种类型的对象 属性字段名equals相等 并且类型一致。则完全可以用commons-beanutils包或者spring包中
的BeanUtils工具类中的copey属性方法。

/**
 * 实体类字段值相同的复制
 *
 * @author 隔壁老王 2017年8月18日
 */
public class CopyBeanUtil {
    static Logger log = LoggerFactory.getLogger(CopyBeanUtil.class);

    /**
     * 复制sour里属性不为空的值到obje为空的属性
     *
     * @param obje    目标实体类
     * @param sour    源实体类
     * @param isCover 是否保留obje类里不为null的属性值(true为保留源值,属性为null则赋值)
     * @return obje
     */
    public static Object Copy(Object obje, Object sour, boolean isCover) {
        Field[] fields = sour.getClass().getDeclaredFields();
        for (int i = 0, j = fields.length; i < j; i++) {
            String propertyName = fields[i].getName();
            Object propertyValue = getProperty(sour, propertyName);
            if (isCover) {
                if (getProperty(obje, propertyName) == null && propertyValue != null) {
                    Object setProperty = setProperty(obje, propertyName, propertyValue);
                }
            } else {
                Object setProperty = setProperty(obje, propertyName, propertyValue);
            }

        }
        return obje;
    }

    /**
     * 复制sour里属性不为空的值到obj里并相加
     *
     * @param obj     目标实体类
     * @param sour    源实体类
     * @param isCover
     * @return obj
     */
    public static Object CopyAndAdd(Object obj, Object sour, boolean isCover) {
        Field[] fields = sour.getClass().getDeclaredFields();
        for (int i = 0, j = fields.length; i < j; i++) {
            String propertyName = fields[i].getName();
            Object sourPropertyValue = getProperty(sour, propertyName);
            Object objPropertyValue = getProperty(obj, propertyName);
            if (isCover) {
                if (objPropertyValue == null && sourPropertyValue != null) {
                    Object setProperty = setProperty(obj, propertyName, sourPropertyValue);
                } else if (objPropertyValue != null && sourPropertyValue == null) {
                    Object setProperty = setProperty(obj, propertyName, objPropertyValue);
                } else if (objPropertyValue != null && sourPropertyValue != null) {
                    Object setProperty = setProperty(obj, propertyName, ((int) sourPropertyValue) + (int) objPropertyValue);
                }
            }

        }
        return obj;
    }


    /**
     * 得到值
     *
     * @param bean
     * @param propertyName
     * @return
     */
    private static Object getProperty(Object bean, String propertyName) {
        Class clazz = bean.getClass();
        try {
            Field field = clazz.getDeclaredField(propertyName);
            Method method = clazz.getDeclaredMethod(getGetterName(field.getName(),field.getType()), new Class[]{});
            return method.invoke(bean, new Object[]{});
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 给bean赋值
     *
     * @param bean
     * @param propertyName
     * @param value
     * @return
     */
    private static Object setProperty(Object bean, String propertyName, Object value) {
        Class clazz = bean.getClass();
        try {
            Field field = clazz.getDeclaredField(propertyName);
            Method method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[]{field.getType()});
            return method.invoke(bean, new Object[]{value});
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 根据变量名得到get方法
     *
     * @param propertyName
     * @return
     */
    private static String getGetterName(String propertyName) {
        String method ;
        if( propertyName.length()>1&& Character.isUpperCase(propertyName.charAt(1))){
             method = "get" +propertyName;
        }else{
            method = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        }
        return method;
    }

    /**
     * 根据变量名和类型获取getter方法
     * @param propertyName
     * @param type
     * @return
     */
    private static String getGetterName(String propertyName, Class<?> type) {
        String method ;
        if(type==Boolean.class|| type==boolean.class){
            if("is".equalsIgnoreCase(propertyName.substring(0, 2))){
                return propertyName;
            }else{
                return "is" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
            }

        }
        if( propertyName.length()>1&& Character.isUpperCase(propertyName.charAt(1))){
            method = "get" +propertyName;
        }else{
            method = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        }
        return method;
    }

    /**
     * 得到setter方法
     *
     * @param propertyName 变量名
     * @return
     */
    private static String getSetterName(String propertyName) {
//        String method = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        String method ;
        if( propertyName.length()>1&& Character.isUpperCase(propertyName.charAt(1))){
            method = "set" +propertyName;
        }else{
            method = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        }
        return method;
    }


    /**
     * 父类集合转成子类集合集合通用方法(子类集合接收父类集合)
     *
     * @param list 父类集合
     * @param <T>  子类
     * @param <E>  父类
     * @return
     */
    public static <T, E> List<T> chang2ChildClassList(List<E> list) {
        List<T> alist = new ArrayList<>();
        for (E o : list) {
            alist.add((T) o);
        }
        return alist;

    }

    /**
     * 属性copy  复制sour里属性和obje里属性值忽略大小写相同的 ,不为空的值赋值到obje里
     * 如果存在属性复杂类型并为有效值慎用或改进
     *
     * @param obje
     * @param sour
     * @param isCover 是否保留obje里面属性值不为空的字段值
     * @return
     */
    public static Object copyByIgnoreCase(Object obje, Object sour, boolean isCover) {

        try {
            Field[] objFields = obje.getClass().getDeclaredFields();

            Field[] sourFields = sour.getClass().getDeclaredFields();
            for (int i = 0; i < sourFields.length; i++) {
                String sourPropertyName = sourFields[i].getName();
                //获取来源对象的属性值
                Object propertyValue = getSourPropertyValue(sour, sourPropertyName);
                for (int j = 0; j < objFields.length; j++) {

                    try {
                        String objPropertyName = objFields[j].getName();
                        if (objPropertyName.equalsIgnoreCase(sourPropertyName)) {
                            if (isCover) {
                                if (getProperty(obje, objPropertyName) == null && propertyValue != null) {
                                    setObjProperty(obje, objPropertyName, propertyValue);
                                }
                            } else {
                                setObjProperty(obje, objPropertyName, propertyValue);
                            }
                            break;
                        }
                    } catch (Exception e) {
                        log.error("给目标bean赋值出错,objPropertyName:{},value:{}",sourPropertyName,propertyValue,e);
                        e.printStackTrace();
                    }
                }

            }
        } catch (SecurityException e) {
            e.printStackTrace();
            log.error("给目标bean赋值出错,obje:{},sour:{}", JSON.toJSONString(obje), JSON.toJSONString(sour),e);
        }
        return obje;
    }

    /**
     * 根据属性名获取的值
     *
     * @param sourceBean
     * @param sourcePropertyName
     * @return
     */
    private static Object getSourPropertyValue(Object sourceBean, String sourcePropertyName) {
        Class clazz = sourceBean.getClass();
        try {
            Field field = clazz.getDeclaredField(sourcePropertyName);
            Method method = clazz.getDeclaredMethod(getGetterName(field.getName(),field.getType()), new Class[]{});
            return method.invoke(sourceBean, new Object[]{});
        } catch (Exception e) {
            log.error("获取属性名(不区分大小写)相似的值赋值出差", e);
        }
        return null;
    }



    /**
     * 给目标bean赋值
     *
     * @param objBean
     * @param sourcePropertyName
     * @param value
     * @return
     */
    private static Object setObjPropertyBySourceProperty(Object objBean, String sourcePropertyName, Object value) {
        Class clazz = objBean.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (int i = 0, j = fields.length; i < j; i++) {
                String propertyName = fields[i].getName();
                if (sourcePropertyName.equalsIgnoreCase(propertyName)) {
                    Field field = clazz.getDeclaredField(propertyName);
                    if (field.getType() == BigDecimal.class) {
                        if (value instanceof String) {
                            value = new BigDecimal(String.valueOf(value));
                        } else if (value instanceof Integer || value instanceof Double) {
//							传double直接new BigDecimal,数会变大
                            value = BigDecimal.valueOf(Double.parseDouble(String.valueOf(value)));
                        }
                    }
                    if (field.getType() == Double.class || field.getType() == double.class) {
                        if (value instanceof BigDecimal) {
                            DecimalFormat df = new DecimalFormat("#.000000");
                            Double v = Double.parseDouble(String.valueOf(value));
                            value = df.format(v);
                        }
                    }

                    Method method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[]{field.getType()});
                    return method.invoke(objBean, new Object[]{value});
                }
            }

        } catch (Exception e) {
        }
        return null;
    }


    /**
     * 给目标bean赋值
     *
     * @param objBean
     * @param propertyName
     * @param value
     * @return
     */
    private static Object setObjProperty(Object objBean, String propertyName, Object value) {
        Class clazz = objBean.getClass();
        try {
            Field field = clazz.getDeclaredField(propertyName);
            if (field.getType() == BigDecimal.class) {
                if (value instanceof String) {
                    value = new BigDecimal(String.valueOf(value));
                } else if (value instanceof Integer || value instanceof Double) {
//							传double直接new BigDecimal,数会变大
                    value = BigDecimal.valueOf(Double.parseDouble(String.valueOf(value)));
                }
            }
            if (field.getType() == Double.class || field.getType() == double.class) {
                if (value instanceof BigDecimal) {
                    DecimalFormat df = new DecimalFormat("#.000000");
                    Double v = Double.parseDouble(String.valueOf(value));
                    value =new BigDecimal(df.format(v));
                }
            }
            if (field.getType() == Integer.class || field.getType() == int.class) {
                if (value instanceof Float) {
                     value = Math.round(Float.parseFloat(String.valueOf(value)));
                }
            }
            Method method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[]{field.getType()});
            log.info("给目标bean赋值,propertyName:{},value:{}",propertyName,value);
            Object obj = method.invoke(objBean, new Object[]{value});
            return obj;

        } catch (Exception e) {
            log.error("给目标bean赋值出错,propertyName:{},value:{}",propertyName,value,e);
        }
        return null;
    }
    public static void main(String[] args) {
//        ReAlarmResult re= new ReAlarmResult();
//        re.setAlarmContent("sdfsdfsd");
//        re.setBlat(2.234343);
//        re.setBlon(34.34324);
//        ReAlarmResult s = new ReAlarmResult();
//        s.setAlarmContent("222");
//        copyByIgnoreCase(s,re,true);
//        System.out.printf(JSON.toJSONString(s));
//        BeanUtils.copyProperties();
        //BeanUtils.copyProperties();
    }

}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/186416.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • pytorch 下载安装全流程详细教程

    pytorch 下载安装全流程详细教程强烈推荐,亲测有效,1.查看cuda版本。2.在官网https://pytorch.org/选择对应的版本。3.复制RunthisCommand,直接下载安装(速度还挺快)。完美

    2022年10月31日
  • vmware15最新激活码2021【中文破解版】[通俗易懂]

    (vmware15最新激活码2021)JetBrains旗下有多款编译器工具(如:IntelliJ、WebStorm、PyCharm等)在各编程领域几乎都占据了垄断地位。建立在开源IntelliJ平台之上,过去15年以来,JetBrains一直在不断发展和完善这个平台。这个平台可以针对您的开发工作流进行微调并且能够提供…

    2022年3月26日
  • 2021年社工必备查询网址汇总[通俗易懂]

    2021年社工必备查询网址汇总[通俗易懂]社工查询网站手机号注册网站查询信用查询国内企业信息政府信息查询身份信息查询驾驶员及车辆信息查询物品资产查询物流查询发票查询金融查询手机信息查询个人信息查询搜索引擎手机号注册网站查询牛查查http://www.newx007.com比REG007更好用的查询手机注册网站的神器信用查询1、信用中国查询内容:工商注册企业和个人、行政许可和处罚网址:http://www.creditchina.gov.cn/2、全国企业信用信息公示查询内容:全国企业工商登记注册信息http://g

    2022年6月1日
  • Tomcat配置appBase为空时BlazeDS找不到endpoint路径[通俗易懂]

    因为有用quartz定时任务,把tomcat的appBase设置为空,以防同时执行2次。但这样BlazeDS初始化时会找不到endpoint路径。 解决方法是把endpointurl中的{context.root}全部改为项目的路径,如项目是webapps\abc,就把所有{context.root}改为abc…

    2022年4月15日
  • 机器学习:准确率(Precision)、召回率(Recall)、F值(F-Measure)、ROC曲线、PR曲线

    机器学习:准确率(Precision)、召回率(Recall)、F值(F-Measure)、ROC曲线、PR曲线以下第一部分内容转载自:机器学习算法中的准确率(Precision)、召回率(Recall)、F值(F-Measure)是怎么一回事摘要:数据挖掘、机器学习和推荐系统中的评测指标—准确率(Precision)、召回率(Recall)、F值(F-Measure)简介。引言:在机器学习、数据挖掘、推荐系统完成建模之后,需要对模型的效果做评价。业内目前常常采用的评价指标有准确率(Precision)、召

    2022年5月13日
  • keyvaluepair_KeyValuePair用法(转)

    keyvaluepair_KeyValuePair用法(转)C#KeyValuePair的用法。结构体,定义可设置或检索的键/值对。也就是说我们可以通过它记录一个键/值对这样的值。比如我们想定义一个ID(int类型)和Name(string类型)这样的键/值对,那么可以这样使用。//////设置键/值对//////privateKeyValuePairSetKeyValuePair(){intintKey=1;stringstrV…

    2022年7月26日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号