Deep Clone From Super Class

Ever had to create an object from another object being super class of the first one? You could just copy each attribute from one to another but that’s pretty annoying if there’s a lot of attributes. I stumbled upon a generic way and like to share it.

Given following situation:

class A {
  // Many many attributes

class B extends A {
  // ...

A a = magicFactory.getA();
B b = (B) a; // not possible because a is no B!



 * Creates and returns deep clone of given source object with given target type.
 * @param source object to be cloned
 * @param target type of resulting object
 * @param <S> type of source object
 * @param <T> type of target object
 * @return deep clone of source object with target type
public static <S, T extends S> T cloneFromSuperClass(final S source, final Class<T> target) {
  return GSON.fromJson(GSON.toJson(source), target);

A a = magicFactory.getA();
B b = cloneFromSuperClass(a, B.class);