简体   繁体   中英

java bean copy by calling getter and setters

Is there a way to deep copy 2 java objects by calling its getter and setter? All the setters and getters are public methods.

Thanks,

  1. Java provides clone() to perform shallow copies but can be extended to perform deep copies. Read here for more details.
  2. Object Serialization technique can be used for the same.

copyProperties(...) in Commons BeanUtils likely does what you want by matching getter/setter across two different beans.

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;
        }
    }
}

prints

bean1 setter
bean1 getter
bean2 setter
Test$Bean1@1f7d2f0e[propbean1=Foo]
Test$Bean2@539c5048[propbean2=Foo]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM