How do I copy an object in Java?

java deep copy object
java copy object by value
java clone object without cloneable
java copy fields from one object to another
java deep copy library
java deep copy list
java copy constructor
java shallow copy

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?

Create a copy constructor:

class DummyBean {
  private String dummy;

  public DummyBean(DummyBean another) {
    this.dummy = another.dummy; // you can access  
  }
}

Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.

Clone() method in Java, How do you assign an object to an object in Java? When we want to copy an object in Java, there're two possibilities that we need to consider — a shallow copy and a deep copy. The shallow copy is the approach when we only copy field values and therefore the copy might be dependant on the original object.

What happens when an object is assigned to another object, Clone() method in Java. Object cloning refers to creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create copy of an object. In this post, we will discuss various methods to copy objects in Java. Copying an object is creating a copy of an existing object in order to modify or move the copied object without impacting the original object. Unlike C++, objects are not passed by value in Java but their references are passed by value instead. Consider below code snippets,

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

SerializationUtils.clone(Object);

Example:

this.myObjectCloned = SerializationUtils.clone(this.object);

Object Cloning in java, In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy isn't dependant on any earlier existing  The basic idea behind deep copy in java is: There is a Java object which is needed to be cloned (deeply). First step is to mark the Model object as Serializable so that the object can converted When the object is read back, we get a deep clone of the original object. Note that this method

Just follow as below:

public class Deletable implements Cloneable{

    private String str;
    public Deletable(){
    }
    public void setStr(String str){
        this.str = str;
    }
    public void display(){
        System.out.println("The String is "+str);
    }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

and wherever you want to get another object, simple perform cloning. e.g:

Deletable del = new Deletable();
Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                 // object, the changes made to this object will
                                 // not be reflected to other object

How to Make a Deep Copy of an Object in Java, In this post, we will discuss various methods to copy Objects in Java. Copying an object is creating a copy of an existing object in order to modify or. That has nothing to do with references/objects. It has everything to do with your code being broken. Copying objects won't fix it, your logic is wrong. Hint: you need a temporary variable. – Kayaman Jan 23 '17 at 16:51 |

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

Copy Objects in Java, The object cloning in java is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object. Java build in mechanism provided a good support for the deep copy of an object, however, we can have a certain limitation. We do not own source code and it is not possible to add those additional constructors. Object hierarchy is complex and needs complex logic to handle all use cases.

Java clone - deep and shallow copy, First statement guarantees that cloned object will have separate memory address assignment. Second statement suggest that original and cloned objects should  The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

How do we copy objects in java?, In Java you can copy an object in several ways, among them, copy constructor and the clone method are the mostly used.Using copy  In Java, there is no operator to create copy of an object. Unlike C++, in Java, if we use assignment operator then it will create a copy of reference variable and not the object. This can be explained by taking an example.

Java Deep Copy - Java Copy Object, Java Deep Copy, java copy list, java copy object, java deep copy vs shallow copy​, java deep copy using serialization, java copy arraylist example code. How do I copy an object in Java? I need to copy an object in Java (i.e. copy the object "by value not by reference" so that the new object is not just a reference to the old). I'm weary of implementing clonable and would prefer to use a copy constructor.

Comments
  • But then he'd have to change his code to DummyBean two = new DummyBean(one); Right?
  • Does this method effectively accomplish the same thing as a deep copy?
  • @MatthewPiziak, to me - this would not be a deep clone since any nested objects would still be referencing the original source instance, not a duplicate unless each reference (non-value type) object supplies the same constructor template as above.
  • @Timmmm: Yes, they will reference the same String but because it is immutable, it is ok. Same goes for primitives. For non-primitives, you would just do copy contructor call recursively. e.g. If DummyBean referenced FooBar then FooBar should have contructor FooBar(FooBar another), and dummy should call this.foobar = new FooBar(another.foobar)
  • @ChristianVielma: No, it won't be "johndoe". Like Timmmm said, the string itself is immutable. With one, setDummy(..) you set the reference in one to point to "johndoe", but not the one in one.
  • Can you please explain what is object contained within another?
  • @Chandra Sekhar "shallow copying creates a new instance of the same class and copies all the fields to the new instance and returns it" that's wrong to mention all the fields,bcz objects don't get copied only the references get copied which points to the same object that old one(original) was pointing to.
  • @sunny - Chandra's description is correct. And so is your description of what happens; I am saying that you have an incorrect understanding of the meaning of "copies all the fields". The field is the reference, it is not the object being referred to. "copying all fields" means "copying all those references". It is good that you pointed out what exactly this means, for anyone else who has the same mis-interpretation as you, of the statement "copying all fields". :)
  • ... if we think in terms of some lower-level OO language, with "pointers" to objects, such a field would contain the address in memory (such as "0x70FF1234") at which the object data is found. That address is the "field value" that is being copied (assigned). You are correct that the end result is that both objects have fields that refer to (point at) the same object.
  • As long as the object implements Serializable
  • In this case cloned object has no reference to the original, if the last one is static.
  • A third party library just to clone object!