类似BeanUtils.copyProperties拷贝对象属性值的方法

--BeanUtils 拷贝对象

package test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 利用反射机制拷贝对象属性值
 * @author sd
 *
 */
public class BeanUtils {
 
 /**
  * 拷贝对象属性值
  * @author sd(chenfang)
  * @dateTime 2012-8-7下午2:47:53
  * @returnType void
  * @param o1 - orig 被拷贝对象
  * @param o2 - dest 拷贝至对象
  */
 public static void copyPriperties(Object o1, Object o2) {
  String fileName, str, getName, setName;
  List fields = new ArrayList();
  Method getMethod = null;
  Method setMethod = null;
  try {
   Class c1 = o1.getClass();
   Class c2 = o2.getClass();
   
   Field[] fs1 = c1.getDeclaredFields();
   Field[] fs2 = c2.getDeclaredFields();
   // 两个类属性比较剔除不相同的属性,只留下相同的属性
   for (int i = 0; i < fs2.length; i++) {
    for (int j = 0; j < fs1.length; j++) {
     if (fs1[j].getName().equals(fs2[i].getName())) {
      fields.add(fs1[j]);
      break;
     }
    }
   }
   if (null != fields && fields.size() > 0) {
    for (int i = 0; i < fields.size(); i++) {
     // 获取属性名称
     Field f = (Field) fields.get(i);
     fileName = f.getName();
     // 属性名第一个字母大写
     str = fileName.substring(0, 1).toUpperCase();
     // 拼凑getXXX和setXXX方法名
     getName = "get" + str + fileName.substring(1);
     setName = "set" + str + fileName.substring(1);
     // 获取get、set方法
     getMethod = c1.getMethod(getName, new Class[] {});
     setMethod = c2.getMethod(setName, new Class[] { f.getType() });
     // 获取属性值
     Object o = getMethod.invoke(o1, new Object[] {});
     // 将属性值放入另一个对象中对应的属性
     setMethod.invoke(o2, new Object[] { o });
    }
   }
  } catch (SecurityException e) {
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  D1 d1 = new D1();
  d1.setDate(new Date());
  d1.setAge(null);
  d1.setScore(null);
  
  D2 d2 = new D2();
  d2.setAge(12);
  BeanUtils.copyPriperties(d1, d2);
  
  System.out.println(d2.toString());
  
  
 }
}

--两个对象

package test;

import java.util.Date;

public class D1 {
 private Date date = null;
 private Integer age=null;
    private Double score=null;
 
 public Date getDate() {
  return date;
 }

 public void setDate(Date date) {
  this.date = date;
 }

 public Integer getAge() {
  return age;
 }

 public void setAge(Integer age) {
  this.age = age;
 }

 public Double getScore() {
  return score;
 }

 public void setScore(Double score) {
  this.score = score;
 }
 
 @Override
 public String toString() {
  return "D1 [date=" + date.toLocaleString() + ", age=" + age + ", score=" + score + "]";
 }
}

 

package test;

import java.util.Date;

public class D2 {
 private Date date = null;
 private Integer age=null;
    private Double score=null;
 
 public Date getDate() {
  return date;
 }

 public void setDate(Date date) {
  this.date = date;
 }

 public Integer getAge() {
  return age;
 }

 public void setAge(Integer age) {
  this.age = age;
 }

 public Double getScore() {
  return score;
 }

 public void setScore(Double score) {
  this.score = score;
 }

 @Override
 public String toString() {
  return "D2 [date=" + date + ", age=" + age + ", score=" + score + "]";
 }

 

}

 

 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BeanUtils.copyProperties方法是Apache Commons BeanUtils库中的一个工具方法,用于将一个Java对象属性拷贝到另一个Java对象中。它可以实现对象之间的属性复制,无需手动逐个设置属性。 使用BeanUtils.copyProperties方法进行属性拷贝时,需要注意以下几点: 1. 属性名称和类型必须在源对象和目标对象中存在且匹配。 2. 属性拷贝是基于属性名称进行匹配的,而不是基于属性的位置。 3. 如果源对象和目标对象中存在相同名称但类型不匹配的属性,会抛出ConversionException异常。 4. 如果源对象中的属性null,则目标对象对应的属性也会被设置为null。 5. 如果源对象和目标对象中存在嵌套对象,也会进行递归拷贝。 下面是一个示例代码,演示了如何使用BeanUtils.copyProperties方法进行属性拷贝: ```java import org.apache.commons.beanutils.BeanUtils; public class Main { public static void main(String[] args) { SourceObject source = new SourceObject(); source.setName("John"); source.setAge(25); TargetObject target = new TargetObject(); try { BeanUtils.copyProperties(target, source); System.out.println(target.getName()); // 输出:John System.out.println(target.getAge()); // 输出:25 } catch (Exception e) { e.printStackTrace(); } } } class SourceObject { private String name; private int age; // 省略getter和setter方法 } class TargetObject { private String name; private int age; // 省略getter和setter方法 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值