一个类把属性值赋值给另一个类的相同的属性

来源:互联网 发布:网络类型有哪些 编辑:程序博客网 时间:2024/06/07 01:51

        在Java开发中,会遇到从前台传过来的参数是一个类,这个类与数据库的实体类有些属性是一致的,有些是不一致的,为了避免相同属性赋值的麻烦,我们最好能有一个通用的复制方法。

        下面这个类便可以帮我们实现(main方法是我用来测试用的,大家使用的时候把它去掉即可)。在Main方法中我给AppointmentOrderParam类初始化并赋值,然后想把这个类的值能够自动赋值给另一个类AppointmentOrder,这两个类大部分属性是一样的,有个别不一样。赋值有个需要注意的地方,那就是在AppointmentOrderParam类中的apointmentTime字段类型是String,而AppointmentOrder类中的同名字段apointmentTime是个Date类型,像这样的情况就不要让它赋值了,跳过即可。判断的根据是根据属性名称和属性类型来判断。如果是String,sourceProperty[i].getPropertyType()得到的返回值是"java.lang.String"类,如果是Date,sourceProperty[j].getPropertyType()得到的返回值是"java.util.Date"类,这两个类型是不一样的。这样就没有问题了。

package com.utils;import com.entity.AppointmentOrder;import com.param.AppointmentOrderParam;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;/** * Created by wangzhipeng on 2017/3/16. */public class CopyUtils {    public static void Copy(Object source, Object dest) throws Exception {        // 获取属性        BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(),Object.class);        PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();        BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(),Object.class);        PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();        try {            for (int i = 0; i < sourceProperty.length; i++) {                                for (int j = 0; j < destProperty.length; j++) {                                        if (sourceProperty[i].getName().equals(destProperty[j].getName())  && sourceProperty[i].getPropertyType() == destProperty[j].getPropertyType()) {                        // 调用source的getter方法和dest的setter方法                        destProperty[j].getWriteMethod().invoke(dest,sourceProperty[i].getReadMethod().invoke(source));                        break;                    }                }            }        } catch (Exception e) {            throw new Exception("属性复制失败:" + e.getMessage());        }    }    public static void main(String[] args) throws Exception{        AppointmentOrderParam appointmentOrderParam = new AppointmentOrderParam();        appointmentOrderParam.setAppointmentTime("2017/05/04");        appointmentOrderParam.setConditionDescription("这个毛病已经由来已久了,以前没钱看,现在有钱了,想彻底根治");        appointmentOrderParam.setExpertId("myh111000");        appointmentOrderParam.setOtherOrderId("0001123ll33");        appointmentOrderParam.setSubscriberName("呼兰芬");        appointmentOrderParam.setSubscriberPhone("11097777");        appointmentOrderParam.setTheDisease("呼吸病");        appointmentOrderParam.setTimeSlot(1);        appointmentOrderParam.setTreatmentAddress("北京第三附属医院");        appointmentOrderParam.setTreatmentPrice(200);        appointmentOrderParam.setUserId("kkk888");        AppointmentOrder appointmentOrder = new AppointmentOrder();        CopyUtils.Copy(appointmentOrderParam,appointmentOrder);        System.out.println(appointmentOrder);    }}


0 0
原创粉丝点击