将⼀个实体类赋值给另⼀个实体类
1. ⾃⼰写⼯具类
下⾯这个类便可以帮我们实现。
在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;
ity.AppointmentOrder;
import com.param.AppointmentOrderParam;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
/**
* 属性赋值
路遥知马力日久见人心
*/五十度灰类似
public class CopyUtils {
public static void Copy(Object source, Object dest)throws Exception {
/
蜈蚣的天敌是什么/ 获取属性
BeanInfo sourceBean = Class(),Object.class);
PropertyDescriptor[] sourceProperty = PropertyDescriptors();
BeanInfo destBean = Class(),Object.class);
PropertyDescriptor[] destProperty = PropertyDescriptors();
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的tter⽅法
饮用水水源保护区
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.tAppointmentTime("2021/01/01");
appointmentOrderParam.tConditionDescription("这个⽑病已经由来已久了,以前没钱看,现在有钱了,想彻底根治");
appointmentOrderParam.tExpertId("myh111000");月落乌啼霜满天江枫渔火对愁眠
appointmentOrderParam.tOtherOrderId("0001123ll33");
appointmentOrderParam.tSubscriberName("呼兰芬");
appointmentOrderParam.tSubscriberPhone("11097777");
appointmentOrderParam.tTheDia("呼吸病");
appointmentOrderParam.tTimeSlot(1);
appointmentOrderParam.tTreatmentAddress("北京第三附属医院");
appointmentOrderParam.tTreatmentPrice(200);
appointmentOrderParam.tUrId("kkk888");
AppointmentOrder appointmentOrder =new AppointmentOrder();
CopyUtils.Copy(appointmentOrderParam,appointmentOrder);
System.out.println(appointmentOrder);
}
}
2. pyProperties()
将 ele 赋值给 eleRes
使⽤场景:
Entity 向 Info 转换
平时我们会写数据库对应的实体类。⽽我们想要返回给前端的结果不想使⽤这个数据库对应的实体类。那么就需要有进⾏⼀个转换。可以使⽤ 这种⽅式。pyProperties(Entity ,Info );
【参考】
1.
2.