Software Development

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

[wp_ad_camp_1]

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:

[wp_ad_camp_2]

Working with Generics

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

[wp_ad_camp_3]

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

Sample usage:

This outputs:

[wp_ad_camp_4]

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

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like