通过调用getter和setter来复制java bean

时间:2011-02-01 04:01:25

标签: java

有没有办法通过调用它的getter和setter来深度复制2个java对象?所有的制定者和吸气者都是公共方法。

谢谢,

2 个答案:

答案 0 :(得分:1)

  1. Java提供clone()来执行浅拷贝,但可以扩展以执行深拷贝。 Read here了解更多详情。
  2. Object Serialization technique can be used for the same.

答案 1 :(得分:1)

Commons BeanUtils中的

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]