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


相关推荐

  • 树莓派运行python命令_《树莓派Python编程入门与实战》——2.2 使用Raspbian命令行…[通俗易懂]

    本节书摘来异步社区《树莓派Python编程入门与实战》一书中的第2章,第2.2节,作者:【美】RichardBlum,更多章节内容可以访问云栖社区“异步社区”公众号查看2.2 使用Raspbian命令行树莓派Python编程入门与实战树莓派第一次启动的时候,没有要求你提供用户名和密码。然而,在初始化启动之后的所有后续启动中,你都会看到Raspbian的登录屏幕。清单2.1显示了如何登录树莓派。默…

    2022年4月12日
    42
  • 《手把手教你学DSP》总结1

    《手把手教你学DSP》总结11.开始学习时不要纠结DSP的具体结构,大体了解有哪些功能模块即可,DSP的工作原理不是重点,在后期使用时再详细弄懂所需结构的详情2.C2000系列即TMS320C2000包括F24XX,C28XX,F28XX为低端型号,C5000系列面向低功耗,C6000系列面向高性能3.TI的DSP型号含义例如:TMS320F2812PGFA  例如:TMS320F2812PGFA

    2022年6月9日
    27
  • 炒黄金入门必备基础知识学习「建议收藏」

    炒黄金入门必备基础知识学习「建议收藏」黄金投资在西方发达国家已经有百年历史了,其运作流程、交易体系都越来越完善,而且投资市场也越来越成熟。黄金市场是国际金融投资的热点。伦敦的现货黄金市场、美国的黄金期货市场、香港金银业贸易场等地的黄金市场组成了全球24小时不间断的黄金投资市场。一、交易介绍国际现货黄金以保证金的方式进行的一种现货交易业务,买卖双方以一定比例的保证金确立买卖合约,该合约可以不必实物交收,买卖双方可以根据市场的变化情…

    2022年5月8日
    36
  • java integer.parseint_java method.invoke

    java integer.parseint_java method.invoke我正在编写一个使用反射来动态查找和调用方法的库.只给出一个对象,一个方法名和一个参数列表,我需要调用给定的方法,就好像方法调用是在代码中显式编写的一样.我一直在使用以下方法,在大多数情况下都可以使用:staticvoidcallMethod(Objectreceiver,StringmethodName,Object[]params){Class>[]paramTypes…

    2022年9月23日
    2
  • ubuntu的source命令_ubuntu installation type

    ubuntu的source命令_ubuntu installation typeGPGerror:No_PUBKEY

    2022年10月13日
    5
  • open函数返回值为0

    open函数返回值为0open函数是我们开发中经常会遇到的,这个函数是对文件设备的打开操作,这个函数会返回一个句柄fd,我们通过这个句柄fd对设备文件读写操作。  我们在对这个fd作判断的时候,经常会用到:    fd=open(filename,O_RDONLY);     If(fd          Printf(“open%serror!\n”,fi

    2022年5月25日
    308

发表回复

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

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