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 ?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With