Does BeanUtils.copyProperties make a deep clone?

happybuddha picture happybuddha · Jun 19, 2013 · Viewed 7.7k times · Source

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 ?

Answer

Daniel Kaplan picture Daniel Kaplan · Jun 19, 2013

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".