java两个对象中相同的属性值复制

本文介绍了一种用于Java环境中两个对象间属性值复制的方法实现。该方法通过反射机制遍历源对象的所有属性,并将它们复制到目标对象的相应属性中,前提是这两个属性名称相同。这种方法在对象之间的数据迁移或初始化新对象时非常有用。
/**
* 两个对象中相同的属性值复制
* @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中实现两个相同类型对象复制有多种方法,以下为你详细介绍: ### 1. 使用构造函数 可以在类中定义一个构造函数,它接受同类型的对象作为参数,然后在构造函数内部将传入对象属性值赋给新对象。示例代码如下: ```java class Person { private String name; private int age; // 普通构造函数 public Person(String name, int age) { this.name = name; this.age = age; } // 复制构造函数 public Person(Person other) { this.name = other.name; this.age = other.age; } public String getName() { return name; } public int getAge() { return age; } } public class Main { public static void main(String[] args) { Person person1 = new Person("Alice", 25); Person person2 = new Person(person1); System.out.println(person2.getName()); // 输出: Alice System.out.println(person2.getAge()); // 输出: 25 } } ``` ### 2. 自定义方法 在类中定义一个方法,用于将另一个同类型对象属性值复制到当前对象。示例代码如下: ```java class Book { private String title; private double price; public Book(String title, double price) { this.title = title; this.price = price; } public void copyFrom(Book other) { this.title = other.title; this.price = other.price; } public String getTitle() { return title; } public double getPrice() { return price; } } public class Main { public static void main(String[] args) { Book book1 = new Book("Java Programming", 39.99); Book book2 = new Book("Initial Title", 0.0); book2.copyFrom(book1); System.out.println(book2.getTitle()); // 输出: Java Programming System.out.println(book2.getPrice()); // 输出: 39.99 } } ``` ### 3. 使用`BeanUtils` `org.apache.commons.beanutils.BeanUtils` 提供了一个便捷的 `copyProperties` 方法,可以将一个对象属性值复制到另一个对象。示例代码如下: ```java import org.apache.commons.beanutils.BeanUtils; class Student { private String name; private int score; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } public class Main { public static void main(String[] args) throws Exception { Student student1 = new Student(); student1.setName("Bob"); student1.setScore(85); Student student2 = new Student(); BeanUtils.copyProperties(student2, student1); System.out.println(student2.getName()); // 输出: Bob System.out.println(student2.getScore()); // 输出: 85 } } ``` 不过需要注意的是,如果两个实体类 `properties` 属性类型不一样,`org.apache.commons.beanutils.BeanUtils` 会抛出 `java.lang.IllegalArgumentException` 异常 [^4]。 ### 4. 使用 `org.springframework.beans.BeanUtils` Spring 框架提供的 `org.springframework.beans.BeanUtils` 也有 `copyProperties` 方法,它在处理属性类型不匹配时不会抛出异常,而是跳过该属性不进行赋 [^4]。示例代码如下: ```java import org.springframework.beans.BeanUtils; class Employee { private String name; private int salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } } public class Main { public static void main(String[] args) { Employee employee1 = new Employee(); employee1.setName("Charlie"); employee1.setSalary(5000); Employee employee2 = new Employee(); BeanUtils.copyProperties(employee1, employee2); System.out.println(employee2.getName()); // 输出: Charlie System.out.println(employee2.getSalary()); // 输出: 5000 } } ``` ### 5. 使用 `Map` 可以将对象属性值存储到 `Map` 中,然后再从 `Map` 中取出赋给另一个对象。示例代码如下: ```java import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; class Fruit { private String name; private double weight; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } } public class Main { public static Map<String, Object> objectToMap(Object obj) throws Exception { Map<String, Object> map = new HashMap<>(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (key.compareToIgnoreCase("class") == 0) { continue; } Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, value); } return map; } public static void mapToObject(Map<String, Object> map, Object obj) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (map.containsKey(key)) { Object value = map.get(key); Method setter = property.getWriteMethod(); setter.invoke(obj, value); } } } public static void main(String[] args) throws Exception { Fruit fruit1 = new Fruit(); fruit1.setName("Apple"); fruit1.setWeight(0.5); Map<String, Object> map = objectToMap(fruit1); Fruit fruit2 = new Fruit(); mapToObject(map, fruit2); System.out.println(fruit2.getName()); // 输出: Apple System.out.println(fruit2.getWeight()); // 输出: 0.5 } } ``` 选择合适的方法取决于具体的业务需求和代码结构 [^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值