Serialization and De-Serialization in Java
Not sure what serialization means for your code? Look no further.
Join the DZone community and get the full member experience.
Join For Freewhen you create a class, you may create an object for that particular class and once we execute/terminate the program, the object is destroyed by itself via the garbage collector thread.
what happens if you want to call that class without re-creating the object? in those cases, what you do is use the serialization concept by converting data into a byte stream.
object serialization is a process used to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running java virtual machine. the reverse process of creating an object from the byte stream is called deserialization . the byte stream created is platform independent. so, the object serialized on one platform can be deserialized on a different platform.
how to make a java class serializable?
serializability can be enabled in your java class by implementing the java.io.serializable interface. it is a marker interface that means it contains no methods or fields and only serves to identify the semantics of being serializable.
what if we are trying to serialize a non-serializable object?
we will get a
runtimeexception
saying: exception in thread "main" java.io.notserializableexception: java.io.objectoutputstream.
what is the serialversionuid?
serialversionuid
is an id, which is stamped on an object when it gets serialized usually with the hashcode of the object. we can find serialversionuid for the object by the
serialver
tool in java.
syntax:
serialver classname
serialversionuid
is used for version control of an object. the consequence of not specifying
serialversionuid
is that when you add or modify any field in the class, then the already-serialized class will not be able to recover because the
serialversionuid
was
generated for the new class and the old serialized object will be different. the java serialization process relies on correct
serialversionuid
for recovering the state of the serialized object and throws java.io.invalidclassexception in case of
serialversionuid
mismatch.
transient keyword
the transient modifier/keyword is applicable only for variables but not for methods and classes.
at the time of serialization, if we don't want to serialize the value of a particular variable to meet security constraints, then we should declare that variable as transient.
while performing serialization, the jvm ignores the original value of the transient variable and save default value to the file. hence, transient means not to serialize.
transient vs. static
a static variable is not part of an object state, and hence, it won't participate in serialization. due to this declaring static variable as transient, there is no use.
final vs. transient
final variables will be participated in serialization directly by the value. hence, declaring a final variable as transient causes no impact.
now, let us consider a program that shows serialization and de-serialization in java.
this pojo class
employee
implements the
serializable
interface:
package com.java.serialization;
import java.io.serializable;
public class employee implements serializable {
private static final long serialversionuid = 1l;
private string serializevaluename;
private transient int nonserializevaluesalary;
public string getserializevaluename() {
return serializevaluename;
}
public void setserializevaluename(string serializevaluename) {
this.serializevaluename = serializevaluename;
}
public int getnonserializevaluesalary() {
return nonserializevaluesalary;
}
public void setnonserializevaluesalary(int nonserializevaluesalary) {
this.nonserializevaluesalary = nonserializevaluesalary;
}
@override
public string tostring() {
return "employee [serializevaluename=" + serializevaluename + "]";
}
}
the following
serializingobject
program instantiates an
employee
object and serializes it to a file.
package com.java.serialization;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.objectoutputstream;
public class serializingobject {
public static void main(string[] args) {
employee employeeoutput = null;
fileoutputstream fos = null;
objectoutputstream oos = null;
employeeoutput = new employee();
employeeoutput.setserializevaluename("aman");
employeeoutput.setnonserializevaluesalary(50000);
try {
fos = new fileoutputstream("employee.ser");
oos = new objectoutputstream(fos);
oos.writeobject(employeeoutput);
system.out.println("serialized data is saved in employee.ser file");
oos.close();
fos.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
output :
serialized data is saved in employee.ser file.
the following
deserializingobject
program deserializes the
employee
object created in the
serializingobject
program.
package com.java.serialization;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.objectinputstream;
public class deserializingobject {
public static void main(string[] args) {
employee employeeinput = null;
fileinputstream fis = null;
objectinputstream ois = null;
try {
fis = new fileinputstream("employee.ser");
ois = new objectinputstream(fis);
employeeinput = (employee)ois.readobject();
system.out.println("serialized data is restored from employee.ser file");
ois.close();
fis.close();
} catch (ioexception | classnotfoundexception e) {
e.printstacktrace();
}
system.out.println("name of employee is : " + employeeinput.getserializevaluename());
system.out.println("salary of employee is : " + employeeinput.getnonserializevaluesalary());
}
}
output:
serialized data is restored from employee.ser file
name of employee is : aman
salary of employee is : 0
Published at DZone with permission of Dev Bhatia. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments