Copying JavaBeans Instances: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(10 intermediate revisions by the same user not shown)
Line 16: Line 16:


{{External|[https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#clone() Javadoc Object.clone()]}}
{{External|[https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#clone() Javadoc Object.clone()]}}
{{External|[https://github.com/ovidiuf/playground/blob/master/java/beans/deep-copy/src/main/java/io/novaordis/playground/java/beans/deepCopy/Something.java NOKB Object.clone() Implementation Example]}}


Essentially,
Essentially, the cloned object should generally behave as follows (though this is not a requirement):


    /**
<syntaxhighlight lang='java'>
    * Creates and returns a copy of this object.  The precise meaning
x.clone() != x
    * of "copy" may depend on the class of the object. The general
x.clone.getClass() == x.getClass();
    * intent is that, for any object {@code x}, the expression:
x.clone().equals(x)
    * <blockquote>
</syntaxhighlight>
    * <pre>
 
    * x.clone() != x</pre></blockquote>
By convention, the returned object should be obtained by calling super.clone().  If a class and all of its superclasses (except Object) obey this convention, x.clone().getClass() == x.getClass() will be true.
    * will be true, and that the expression:
 
    * <blockquote>
The general intention behind cloning is to obtain an identical, but independent object, so the clone() method should deep-copy any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing reference to these objects with reference to copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.
    * <pre>
 
    * x.clone().getClass() == x.getClass()</pre></blockquote>
If the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.
    * will be {@code true}, but these are not absolute requirements.
 
    * While it is typically the case that:
Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
    * <blockquote>
 
    * <pre>
Implementation example:
    * x.clone().equals(x)</pre></blockquote>
 
    * will be {@code true}, this is not an absolute requirement.
<syntaxhighlight lang='java'>
    * <p>
public class Something implements Cloneable {
    * By convention, the returned object should be obtained by calling
 
    * {@code super.clone}.  If a class and all of its superclasses (except
    private long id;
    * {@code Object}) obey this convention, it will be the case that
    private String name;
    * {@code x.clone().getClass() == x.getClass()}.
    private SomethingElse somethingElse;
    * <p>
 
    * By convention, the object returned by this method should be independent
    Something(long id, String name, SomethingElse somethingElse) {
    * of this object (which is being cloned).  To achieve this independence,
 
    * it may be necessary to modify one or more fields of the object returned
        this.id = id;
    * by {@code super.clone} before returning it.  Typically, this means
        this.name = name;
    * copying any mutable objects that comprise the internal "deep structure"
        this.somethingElse = somethingElse;
    * of the object being cloned and replacing the references to these
    }
    * objects with references to the copies. If a class contains only
 
    * primitive fields or references to immutable objects, then it is usually
    @Override
    * the case that no fields in the object returned by {@code super.clone}
    public Something clone() {
    * need to be modified.
 
    * <p>
        try {
    * The method {@code clone} for class {@code Object} performs a
 
    * specific cloning operation. First, if the class of this object does
            Something c =  (Something) super.clone();
    * not implement the interface {@code Cloneable}, then a
 
    * {@code CloneNotSupportedException} is thrown. Note that all arrays
            //
    * are considered to implement the interface {@code Cloneable} and that
            // no need to copy members that are immutable (id, name), super.clone() copies references for us ...
    * the return type of the {@code clone} method of an array type {@code T[]}
            //
    * is {@code T[]} where T is any reference or primitive type.
 
    * Otherwise, this method creates a new instance of the class of this
            //
    * object and initializes all its fields with exactly the contents of
            // ... but we need to clone mutable members
    * the corresponding fields of this object, as if by assignment; the
            //
    * contents of the fields are not themselves cloned. Thus, this method
 
    * performs a "shallow copy" of this object, not a "deep copy" operation.
            c.somethingElse = somethingElse.clone();
    * <p>
 
    * The class {@code Object} does not itself implement the interface
            return c;
    * {@code Cloneable}, so calling the {@code clone} method on an object
        }
    * whose class is {@code Object} will result in throwing an
        catch (CloneNotSupportedException e) {
    * exception at run time.
 
    *
            throw new IllegalStateException(e);
    * @return     a clone of this instance.
        }
    * @throws  CloneNotSupportedException  if the object's class does not
    }
    *              support the {@code Cloneable} interface. Subclasses
 
    *              that override the {@code clone} method can also
    @Override
    *              throw this exception to indicate that an instance cannot
    public String toString() {
    *              be cloned.
 
    * @see java.lang.Cloneable
        return id + ": " + name + "(" + somethingElse + ")";
    */
    }
 
    @Override
    public boolean equals(Object o) {
 
        if (this == o) {
 
            return true;
        }
 
        if (name == null) {
 
            return false;
        }
 
        if (somethingElse == null) {
 
            return false;
        }
 
        if (!(o instanceof Something)) {
 
            return false;
        }
 
        Something that = (Something)o;
        return id == that.id && name.equals(that.name) && somethingElse.equals(that.somethingElse);
    }
 
    @Override
    public int hashCode() {
 
        return
                Long.hashCode(id) +
                        17 * (name == null ? 0 : name.hashCode()) +
                        19 * (somethingElse == null ? 0 : somethingElse.hashCode());
    }
}
</syntaxhighlight>
 
<syntaxhighlight lang='java'>
public class SomethingElse implements Cloneable {
 
    private String color;
 
    public SomethingElse(String color) {
 
        this.color = color;
    }
 
    public String getColor() {
 
        return color;
    }
 
    public void setColor(String color) {
 
        this.color = color;
    }
 
    @Override
    public SomethingElse clone() {
 
        try {
 
            //
            // no need to copy members that are immutable (id, name), super.clone() copies references for us
            //
 
            return (SomethingElse) super.clone();
        }
        catch (CloneNotSupportedException e) {
 
            throw new IllegalStateException(e);
        }
    }
 
    @Override
    public String toString() {
 
        return color;
    }
 
    @Override
    public boolean equals(Object o) {
 
        if (this == o) {
 
            return true;
        }
 
        if (color == null) {
 
            return false;
        }
 
        if (!(o instanceof SomethingElse)) {
 
            return false;
        }
 
        SomethingElse that = (SomethingElse)o;
        return color.equals(that.color);
    }
 
    @Override
    public int hashCode() {
 
        return color == null ? 0 : color.hashCode();
    }
}
</syntaxhighlight>


=BeanUtils=
=BeanUtils=


<tt>org.apache.commons.beanutils.BeanUtils</tt> is a utility method for populating JavaBeans properties via reflection. This method can be used even if we don't have access to the JavaBeans instance class code.
<tt>org.apache.commons.beanutils.BeanUtils</tt> is a utility method for populating JavaBeans properties via reflection. This method can be used even if we don't have access to the JavaBeans instance class code, however it is obviously less performant than [[#Object.clone.28.29|Object.clone()]].
 
<syntaxhighlight lang='java'>
import org.springframework.beans.BeanUtils;
 
Object src = ...;
Object dest = ...;
BeanUtils.copyProperties(src, dest);
</syntaxhighlight>

Latest revision as of 07:02, 6 December 2018

External

Internal

Overview

This article describes methods of copying Java Bean instances in such a way that changing the copy leaves the original object intact.

Object.clone()

This method can be used when we have access to the JavaBeans instance class code.

Javadoc Object.clone()
NOKB Object.clone() Implementation Example

Essentially, the cloned object should generally behave as follows (though this is not a requirement):

 x.clone() != x
 x.clone.getClass() == x.getClass();
 x.clone().equals(x)

By convention, the returned object should be obtained by calling super.clone(). If a class and all of its superclasses (except Object) obey this convention, x.clone().getClass() == x.getClass() will be true.

The general intention behind cloning is to obtain an identical, but independent object, so the clone() method should deep-copy any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing reference to these objects with reference to copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.

If the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

Implementation example:

public class Something implements Cloneable {

    private long id;
    private String name;
    private SomethingElse somethingElse;

    Something(long id, String name, SomethingElse somethingElse) {

        this.id = id;
        this.name = name;
        this.somethingElse = somethingElse;
    }

    @Override
    public Something clone() {

        try {

            Something c =  (Something) super.clone();

            //
            // no need to copy members that are immutable (id, name), super.clone() copies references for us ...
            //

            //
            // ... but we need to clone mutable members
            //

            c.somethingElse = somethingElse.clone();

            return c;
        }
        catch (CloneNotSupportedException e) {

            throw new IllegalStateException(e);
        }
    }

    @Override
    public String toString() {

        return id + ": " + name + "(" + somethingElse + ")";
    }

    @Override
    public boolean equals(Object o) {

        if (this == o) {

            return true;
        }

        if (name == null) {

            return false;
        }

        if (somethingElse == null) {

            return false;
        }

        if (!(o instanceof Something)) {

            return false;
        }

        Something that = (Something)o;
        return id == that.id && name.equals(that.name) && somethingElse.equals(that.somethingElse);
    }

    @Override
    public int hashCode() {

        return
                Long.hashCode(id) +
                        17 * (name == null ? 0 : name.hashCode()) +
                        19 * (somethingElse == null ? 0 : somethingElse.hashCode());
    }
}
public class SomethingElse implements Cloneable {

    private String color;

    public SomethingElse(String color) {

        this.color = color;
    }

    public String getColor() {

        return color;
    }

    public void setColor(String color) {

        this.color = color;
    }

    @Override
    public SomethingElse clone() {

        try {

            //
            // no need to copy members that are immutable (id, name), super.clone() copies references for us
            //

            return (SomethingElse) super.clone();
        }
        catch (CloneNotSupportedException e) {

            throw new IllegalStateException(e);
        }
    }

    @Override
    public String toString() {

        return color;
    }

    @Override
    public boolean equals(Object o) {

        if (this == o) {

            return true;
        }

        if (color == null) {

            return false;
        }

        if (!(o instanceof SomethingElse)) {

            return false;
        }

        SomethingElse that = (SomethingElse)o;
        return color.equals(that.color);
    }

    @Override
    public int hashCode() {

        return color == null ? 0 : color.hashCode();
    }
}

BeanUtils

org.apache.commons.beanutils.BeanUtils is a utility method for populating JavaBeans properties via reflection. This method can be used even if we don't have access to the JavaBeans instance class code, however it is obviously less performant than Object.clone().

import org.springframework.beans.BeanUtils;

Object src = ...;
Object dest = ...;
BeanUtils.copyProperties(src, dest);