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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • vue+axios上传文件

    vue+axios上传文件vue+axios上传文件

    2022年6月15日
    32
  • Visual Studio中C++关于Unicode字符集和多字节字符集

    Visual Studio中C++关于Unicode字符集和多字节字符集1.Unicode字符集  原本标准字符集为8位的ASCII码,但世界上的书写语言不能简单地用256个8位代码即一字节表示,就试更宽的值,例如16位值。这就是Unicode非常简单的原理。与混乱的256字符代码映射,以及含有一些单字节代码和一些双字节代码的双字节字符集不同,Unicode是统一的16位系统,这样就允许表示65536个字符。在这里会高兴地告诉你前128个Unicode字符(1

    2025年7月24日
    4
  • 关于CommandType.StoredProcedure输出参数访问问题

    关于CommandType.StoredProcedure输出参数访问问题MSDN解释:当您将 Command 对象用于存储过程时,可以将 Command 对象的 CommandType 属性设置为 StoredProcedure。当 CommandType 为 StoredProcedure 时,可以使用 Command 的 Parameters 属性来访问输入及输出参数和返回值。无论调用哪一个 Execute 方法,都可以访问 Parameters 属性。但是,

    2022年7月26日
    9
  • lm opencv 算法_Levenberg–Marquardt算法学习(和matlab的LM算法对比)[通俗易懂]

    lm opencv 算法_Levenberg–Marquardt算法学习(和matlab的LM算法对比)[通俗易懂]回顾高斯牛顿算法,引入LM算法惩罚因子的计算(迭代步子的计算)完整的算法流程及代码样例1.回顾高斯牛顿,引入LM算法根据之前的博文:Gauss-Newton算法学习假设我们研究如下形式的非线性最小二乘问题:r(x)为某个问题的残差residual,是关于x的非线性函数。我们知道高斯牛顿法的迭代公式:Levenberg–Marquardt算法是对高斯牛顿的改进,在迭代步长上略有不同:最…

    2022年9月30日
    4
  • centos7怎么退出vi_centos7怎么退出vi

    centos7怎么退出vi_centos7怎么退出vi一、首先用vi命令打卡要编辑的文件:注意:vi命令的使用如下打开或新建文件,并将光标至于第一行首:[root@centos6/]#vi/etc/my.cnf打开文件,并将光标移至最后一行行首:[root@centos6/]#vi+/etc/my.cnf打开文件,并将光标置于第n行首:[root@centos6/]#vi+n/etc/my.cnf打开文件,并将光标置于第一个与pattern匹配的串处…

    2022年9月30日
    2
  • TortoiseSVN中分支和合并实践

    TortoiseSVN中分支和合并实践

    2021年8月19日
    67

发表回复

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

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