In this tutorial , i am going to tell you about java object cloning ( Cloning Java Object ) using Serialization.The purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again.The object you want to serialize, that respective class should implement the marker interface serializable and Cloneable. It just informs the compiler that this java class can be serialized and you are going to cloning a object. You can tag properties that should not be serialized as transient.The idea is simple: Write the object to an array using Java Object Serialization ’s ObjectOutputStream and then use ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects.
Here is the Student.java class, that's Object we want to Serialize.
package cloneobject;
import java.io.Serializable;
public class Student implements Serializable,Cloneable {
private String studId;
private String StudName;
private String studAdd;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getStudName() {
return StudName;
}
public void setStudName(String StudName) {
this.StudName = StudName;
}
public String getStudAdd() {
return studAdd;
}
public void setStudAdd(String studAdd) {
this.studAdd = studAdd;
}
public String getStudId() {
return studId;
}
public void setStudId(String studId) {
this.studId = studId;
}
@Override
public String toString() {
return "studentInfo [studentId=" + studId + ", studentName=" + StudName + ", studentAddress=" + studAdd+"]";
}
}
Here is the CloneProvider.java class:
package cloneobject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class CloneProvider {
private CloneProvider(){}
public static Object getClone(Object object) throws Exception{
Object clone=null;
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();
byte [] byteData = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
clone = (Object) new ObjectInputStream(bais).readObject();
}catch(Exception ex){
throw ex;
}
return clone;
}
}
Here is the Main.java class:
package cloneobject;
public class Main {
public static void main(String[] args) throws Exception {
Student student = new Student();
student.setStudId("stud1A");
student.setStudName("Ram");
student.setStudAdd("delhi");
Student studentClone = (Student)CloneProvider.getClone(student);
System.out.println("student Clone :"+studentClone.toString());
}
}
Download Source Code
Click here to download complete source code
0 comments:
Post a Comment