Cloning an Object Using Reflection

Here’s a quick and dirty way to do a shallow copy of an object by overriding the clone method of Object. If you want to do deep copying, you’ll have to fidget with this a little more…or maybe I’ll do another blog about doing recursive cloning for deep copying. We’ll see.

In order to make this as generic and reusable as possible, create the clone method and put it in another class. For instance, maybe you have a Utility class or something like that, that has a lot of static methods in it or something? Well, let’s pretend you do and stick the static clone method in there.

public static Object clone(Object o) { Object clone = null;   try { clone = o.getClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }   // Walk up the superclass hierarchy for (Class obj = o.getClass(); !obj.equals(Object.class); obj = obj.getSuperclass()) { Field[] fields = obj.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); try { // for each class/suerclass, copy all fields // from this object to the clone fields[i].set(clone, fields[i].get(o)); } catch (IllegalArgumentException e){} catch (IllegalAccessException e){} } } return clone; }

Now, to use this method, just override clone() in your class, making sure your Utility class has been imported, and do the appropriate casting.

@Override public MyClass clone() { return (MyClass)Utility.clone(this); }
Scroll to Top