0

Clone Objects in Java with Generics using Apache Commons Lang ObjectUtils

This post demonstrates how to clone objects in Java with Generics using Apache Commons Lang ObjectUtils.

ObjectUtils

ObjectUtils is utility class from Apache Foundation that can be used to clone objects in Java. It is part of a distributable library called Apache Commons Lang.

One of its methods that is of interest to us is the static method clone(T obj) .

Apache Commons Lang Javadoc

Cloneable Interface

To clone something, it has to be cloneable. Technically speaking, a class has to implement the java.lang.Cloneable and create a non-static no-arg method that calls super.clone() and returns a clone (of type java.lang.Object ) of that class’ object.

For instance:

Working with Generics

Okay! Now we have a cloneable class. Let’s create a generic course for students.

One line 18, we used ObjectUtils.clone(T object) .

Sample usage:

This outputs:

Note from the output that iStudent and clonedMe objects are different.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert