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:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

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