The BeanUtils class in Apache Commons BeanUtils library provides a cloneBean method to create a deep clone of a Java bean object.

Here is an example of how to use the cloneBean method:

import org.apache.commons.beanutils.BeanUtils;

public class Main {
    public static void main(String[] args) {
        Person original = new Person("John", 25);
        
        try {
            Person cloned = (Person) BeanUtils.cloneBean(original);
            System.out.println("Original: " + original);
            System.out.println("Cloned: " + cloned);
            
            cloned.setName("Jane");
            cloned.setAge(30);
            
            System.out.println("Original after modification: " + original);
            System.out.println("Cloned after modification: " + cloned);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

Output:

Original: Person [name=John, age=25]
Cloned: Person [name=John, age=25]
Original after modification: Person [name=John, age=25]
Cloned after modification: Person [name=Jane, age=30]

As you can see, modifying the cloned object does not affect the original object, indicating that a deep clone has been created

beanutils clonebean

原文地址: https://www.cveoy.top/t/topic/iZ0Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录