Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does BeanUtils.copyProperties make a deep clone?

To test this, I quickly whipped up the following :

public class Test {

public static void main(String[] args) {
try {
    Employee e = new Employee();
    e.setName("A");
    Employee y = new Employee();
//  y=e;
    BeanUtils.copyProperties(y, e);
    e.setName("B");
    System.out.println(y.getName());
} catch (Exception e) {
    e.printStackTrace();
}

}

}   
class Employee{
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

This should have printed A instead it prints null. What went wrong here ? How can I really copy properties from one object to another (and not have them point to the same values), and does BeanUtils.copyProperties create a deep copy in the first place ?

like image 670
happybuddha Avatar asked Oct 21 '22 07:10

happybuddha


1 Answers

You need to make your Employee class public. This code worked for me (and compiles):

package com.sandbox;

import org.apache.commons.beanutils.BeanUtils;

public class Sandbox {

    public static void main(String[] args) {
        try {
            Employee e = new Employee();
            e.setName("A");
            Employee y = new Employee();
//  y=e;
            BeanUtils.copyProperties(y, e);
            e.setName("B");
            System.out.println(y.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static class Employee {
        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }
}

When I removed the public from Employee, it printed "null".

like image 124
Daniel Kaplan Avatar answered Oct 30 '22 20:10

Daniel Kaplan