需求:在不同类之间直接拷贝所有属性名称相同的属性值。
例如:
public class Class1 {
public int i;
public long l;
public String s;
public List<String> ls;
}
public class Class2{
public int i;
public long l;
public String s;
public List<String> ls;
//other members.
}
一、方法1:自己实现代码
http://blog.csdn.net/isea533/article/details/7851167
下面是一个简单的对象属性复制方法:
复制的对象必须同时拥有setter和getter方法...只有一个的时候会报异常,都没有的时候就不复制..
- import java.beans.BeanInfo;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- public class CopyUtil{
- 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());
- }
- }
- }
二、方法2:BeanUtils.copyProperties(destObj, srcObj);
注意:
1、该方法要求属性类型相同。
2、需要import org.apache.commons.beanutils.PropertyUtils;
而不是com.sun.import org.apache.commons.beanutils.PropertyUtils;//该库中没有该方法。
三、方法3:PropertyUtils.copyProperties(destObj, srcObj);
注意:
1、该方法对不同类型的属性进行强制转换。
2、需要import org.apache.commons.beanutils.PropertyUtils;
而不是com.sun.import org.apache.commons.beanutils.PropertyUtils;//该库中没有该方法。