Cloning via the Cloning library

A deep copy is needed when an object depends on another object. Performing a deep copy means copying the object, including its chain of dependencies. For example, let's assume that Point has a field of the Radius type:

public class Radius {

private int start;
private int end;

// getters and setters
}

public class Point {

private double x;
private double y;
private Radius radius;

public Point(double x, double y, Radius radius) {
this.x = x;
this.y = y;
this.radius = radius;
}

// getters and setters
}

Performing a shallow copy of Point will create a copy of x and y, but will not create a copy of the radius object. This means that modifications that affect the radius object will be reflected in the clone as well. It's time for a deep copy.

A cumbersome solution will involve adapting the shallow copy techniques previously presented to support a deep copy. Fortunately, there are a few solutions that can be applied out of the box, and one of them is the Cloning library (https://github.com/kostaskougios/cloning):

import com.rits.cloning.Cloner;
...
Point point = new Point(...);
Cloner cloner = new Cloner();
Point clone = cloner.deepClone(point);

The code is self-explanatory. Notice that the Cloning library comes with several other goodies as well, as can be seen in the following screenshot:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.239.118