java复制两个属性相同类的值

本文介绍如何使用Apache Commons BeanUtils库中的copyProperties方法在Java中高效地复制Bean属性,避免手动设置每个字段,适用于不能通过继承关系实现数据封装的情况。

需要导入的包:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

BeanUtils.copyProperties(target,source);
source —— 复制源 ,有值的。
target —— 赋值目标,空的,赋值给他

导包的时候:import org.apache.commons.beanutils.BeanUtils;
是 阿帕奇的这个jar包, 然后在抛异常。就可以了
但是我需要用本地的一个类去封装这些数据,而且不能通过继承(子类父类)的关系去实现,实际开发中经常会遇到这种情况。怎么办呢?别告诉我你想一个一个 localBean.setUserId(longDistance.getUserId())……, 那我告诉你我要封装的数据其实有二十几个字段,你给我去一个一个set!

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]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值