class

Generic deep copy

This is an example of how to make a generic copy of a class, using Java reflection. In order to make a generic copy of a class we have created two classes and then copied the one to the other, as described below:

  • We have created two classes A and B. B class has a String and an int field and overrides the toString() method inherited from Object. A class has two int fields, and a B field and also overrides the toString() method inherited from Object.
  • We have also created a class, GenericCopy, that consists of a method, static >T< void copyFields(T from, T to). The method reads each Field from a source class, using getClass(), getFields() API methods of Class, and for each one of them checks if its type is Primitive, using the boolean isPrimitivish(Class c) method of GenericCopy.
  • In boolean isPrimitivish(Class c) method the type of each field is checked and returned. The getType() API method of Field is used to get the type of each field. If a field has a primitive type or its type is equal to one of the classes that wrap the values of the primitive types, then this field in the target class is replaced with the value of the same field from the source class. Else, the copyFields(T from, T to) method is called for the specified field.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.lang.reflect.Field;

public class GenericCopy {

    /**
     * Deep-copies the values from one object to the other
     *
     */
    public static void main(String[] args) {


  A a1 = new A(1, 2, new B("string 1", 10));


  A a2 = new A(3, 4, new B("string 2", 20));


  System.out.println("a1 is :" + a1);

  System.out.println("a2 is :" + a2);


  copyFields(a1, a2);

  

  System.out.println("After copying...");


  System.out.println("a1 is :" + a1);

  System.out.println("a2 is :" + a2);

    }

    public static <T> void copyFields(T from, T to) {


  for (Field f : from.getClass().getFields()) {



try {


    if (isPrimitivish(f.getType())) {



  f.set(to, f.get(from));


    } else {



  copyFields(f.get(from), f.get(to));


    }


} catch (IllegalArgumentException | IllegalAccessException e) {


    e.printStackTrace();


}

  }
    }

    private static boolean isPrimitivish(Class c) {

  return c.isPrimitive() || c == String.class || c == Boolean.class


    || c == Byte.class || c == Short.class || c == Character.class


    || c == Integer.class || c == Float.class || c == Double.class


    || c == Long.class;
    }
}

class A {

   public int x;
   public int y;
   public B bObj;

    public A(int x, int y, B b) {


  this.x = x;

  this.y = y;

  this.bObj = b;

    }

    @Override
    public String toString() {

  return "[" + this.x + "," + this.y + "," + this.bObj.toString() + "]";
    }
}

class B {

    public String str;
    public int z;

    public B(String str, int z) {


  this.str = str;

  this.z = z;

    }

    @Override
    public String toString() {

  return "[" + this.str + "," + this.z + "]";
    }
}

Output:

a1 is :[1,2,[string 1,10]]
a2 is :[3,4,[string 2,20]]
After copying...
a1 is :[1,2,[string 1,10]]
a2 is :[1,2,[string 1,10]]

 
This was an example of how to make a generic copy of a class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button