/**
* 两个对象中相同的属性值复制
* @param source
* @param dest
* @throws Exception
*/
public static void Copy(Object source, Object dest)throws Exception {
//获取属性
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);
PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
BeanInfo destBean = Introspector.getBeanInfo(dest.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(dest, sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
}catch(Exception e){
throw new Exception("属性复制失败:"+e.getMessage());
}
}
* 两个对象中相同的属性值复制
* @param source
* @param dest
* @throws Exception
*/
public static void Copy(Object source, Object dest)throws Exception {
//获取属性
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);
PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
BeanInfo destBean = Introspector.getBeanInfo(dest.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(dest, sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
}catch(Exception e){
throw new Exception("属性复制失败:"+e.getMessage());
}
}
本文介绍了一种用于Java环境中两个对象间属性值复制的方法实现。该方法通过反射机制遍历源对象的所有属性,并将它们复制到目标对象的相应属性中,前提是这两个属性名称相同。这种方法在对象之间的数据迁移或初始化新对象时非常有用。
2639

被折叠的 条评论
为什么被折叠?



