How do I copy an object in Java?

2018-12-31 00:49发布

Consider the code below:

DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'

DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'

dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'

So, I want to copy the dum to dumtwo and change dum without affecting the dumtwo. But the code above is not doing that. When I change something in dum, the same change is happening in dumtwo also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of dum and assign it to dumtwo?

21条回答
大哥的爱人
2楼-- · 2018-12-31 00:52
class DB {
  private String dummy;

  public DB(DB one) {
    this.dummy = one.dummy; 
  }
}
查看更多
看风景的人
3楼-- · 2018-12-31 00:52

You can deep copy automatically with XStream, from http://x-stream.github.io/:

XStream is a simple library to serialize objects to XML and back again.

Add it to your project (if using maven)

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.3.1</version>                
</dependency>

Then

DummyBean dum = new DummyBean();
dum.setDummy("foo");
DummyBean dumCopy = (DummyBean) XSTREAM.fromXML(XSTREAM.toXML(dum));

With this you have a copy without the need to implement any cloning interface.

查看更多
骚的不知所云
4楼-- · 2018-12-31 00:53

Why is there no answer for using Reflection API?

private static Object cloneObject(Object obj){
        try{
            Object clone = obj.getClass().newInstance();
            for (Field field : obj.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                field.set(clone, field.get(obj));
            }
            return clone;
        }catch(Exception e){
            return null;
        }
    }

It's really simple.

EDIT: Include child object via recursion

private static Object cloneObject(Object obj){
        try{
            Object clone = obj.getClass().newInstance();
            for (Field field : obj.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                if(field.get(obj) == null || Modifier.isFinal(field.getModifiers())){
                    continue;
                }
                if(field.getType().isPrimitive() || field.getType().equals(String.class)
                        || field.getType().getSuperclass().equals(Number.class)
                        || field.getType().equals(Boolean.class)){
                    field.set(clone, field.get(obj));
                }else{
                    Object childObj = field.get(obj);
                    if(childObj == obj){
                        field.set(clone, clone);
                    }else{
                        field.set(clone, cloneObject(field.get(obj)));
                    }
                }
            }
            return clone;
        }catch(Exception e){
            return null;
        }
    }
查看更多
何处买醉
5楼-- · 2018-12-31 00:56

Yes, you are just making a reference to the object. You can clone the object if it implements Cloneable.

Check out this wiki article about copying objects.

Refer here: Object copying

查看更多
明月照影归
6楼-- · 2018-12-31 01:01

In the package import org.apache.commons.lang.SerializationUtils; there is a method:

SerializationUtils.clone(Object);

Example:

this.myObjectCloned = SerializationUtils.clone(this.object);
查看更多
栀子花@的思念
7楼-- · 2018-12-31 01:01

You can try to implement Cloneable and use the clone() method; however, if you use the clone method you should - by standard - ALWAYS override Object's public Object clone() method.

查看更多
登录 后发表回答