How to clone object via Serialization
Jodd is an open-source java library with lot of reusable components and feature rich utilities.
This requires the library jodd-3.3.2.jar to be in classpath.
The following example shows how to use ObjectUtil.cloneViaSerialization() API.
It creates a deep copy of the given object.
package com.bethecoder.tutorials.jodd.common;
public class Student implements java.io.Serializable {
private static final long serialVersionUID = - 5962595557796049374L ;
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
package com.bethecoder.tutorials.jodd.encode;
import java.io.IOException;
import jodd.util.ObjectUtil;
import com.bethecoder.tutorials.jodd.common.Student;
public class ObjectCloneTest {
/**
* @param args
* @throws ClassNotFoundException
* @throws IOException
*/
public static void main ( String [] args ) throws IOException, ClassNotFoundException {
Student std = new Student ( "Sriram" , 2 , "Chess" ) ;
Student std2 = ( Student ) ObjectUtil.cloneViaSerialization ( std ) ;
System.out.println ( std ) ;
System.out.println ( std2 ) ;
System.out.println ( std.hashCode ()) ;
System.out.println ( std2.hashCode ()) ;
}
}
It gives the following output,
Student[name = Sriram, age = 2, hobby = Chess]
Student[name = Sriram, age = 2, hobby = Chess]
21174459
9023134