Copying JavaBeans Instances

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

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