package com.duanxin;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import com.jy.lexiu.api.evaluation.entity.LpEvaluationPart;
import com.jy.lexiu.business.picc.beans.LpEvaluPart;
public class Test {
/**
*
* @param source 被复制的实体类对象
* @param to 复制完后的实体类对象
* @throws Exception
*/
public static void Copy(Object source, Object to) throws Exception {
// 获取属性
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(),java.lang.Object.class);
PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
BeanInfo destBean = Introspector.getBeanInfo(to.getClass(),java.lang.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())) {
// 调用source的getter方法和dest的setter方法
destProperty[j].getWriteMethod().invoke(to,sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
} catch (Exception e) {
throw new Exception("属性复制失败:" + e.getMessage());
}
}
public static void main(String args[]) throws Exception{
LpEvaluationPart lpEvaluationPart = new LpEvaluationPart();
LpEvaluPart part=new LpEvaluPart();
part.setCheckWaiting("1");
part.setCreator("2");
Copy(part,lpEvaluationPart);
System.out.println(lpEvaluationPart.getCheckWaiting()+" "+lpEvaluationPart.getCreator());
}
}
天易41----java实现两个实体类属性之间的复制
最新推荐文章于 2024-08-14 16:16:50 发布