有没有办法通过调用它的getter和setter来深度复制2个java对象?所有的制定者和吸气者都是公共方法。
谢谢,
答案 0 :(得分:1)
答案 1 :(得分:1)
copyProperties(...)可能通过在两个不同的bean中匹配getter / setter来实现你想要的。
public class Test
{
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
{
new Test().run();
}
private void run() throws IllegalAccessException, InvocationTargetException
{
Bean1 one = new Bean1();
one.setProp1("Foo");
Bean2 two = new Bean2();
BeanUtils.copyProperties(two, one);
System.out.println(ToStringBuilder.reflectionToString(one));
System.out.println(ToStringBuilder.reflectionToString(two));
}
public class Bean1
{
private String propbean1;
public String getProp1()
{
System.out.println("bean1 getter");
return propbean1;
}
public void setProp1(String s)
{
System.out.println("bean1 setter");
propbean1 = s;
}
}
public class Bean2
{
private String propbean2;
public String getProp1()
{
System.out.println("bean2 getter");
return propbean2;
}
public void setProp1(String s)
{
System.out.println("bean2 setter");
propbean2 = s;
}
}
}
打印
bean1 setter
bean1 getter
bean2 setter
Test$Bean1@1f7d2f0e[propbean1=Foo]
Test$Bean2@539c5048[propbean2=Foo]