Вы находитесь на странице: 1из 13

29/8/2015

Serializationinjava

KnowledgeBase

ANDROID

JobBoard

JAVA

JoinUs

About

JVM LANGUAGES

SOFTWARE DEVELOPMENT

AGILE

CAREER

COMMUNICATIONS

DEVOPS

Search...

META JCG

HomeJavaCoreJavaSerializationinjava

ABOUT ARPIT MANDLIYA


IamjavadeveloperatTataConsultancyServicesLtd.MycurrentareaofinterestareJ2EE,webdevelopmentandjavadesign
patterns.Iamtechnologyenthusiasttryingtoexplorenewtechnologies.Insparetime,Iloveblogging.

NEWSLETTER

121704insidersarealreadyenjoyin

Serialization in java
Postedby:ArpitMandliya inCoreJava March12th,2013

Javaprovidesmechanismcalledserializationtopersistsjavaobjectsinaformoforderedorsequenceofbytesthatincludestheobjectsdata
aswellasinformationabouttheobjectstypeandthetypesofdatastoredintheobject.Soifwehaveserializeanyobjectthenitcanberead
anddeserializeitusingobjectstypeandotherinformationsowecanretrieveoriginalobject.
ClassesObjectInputStreamandObjectOutputStreamarehighlevelstreamsthatcontainthemethodsforserializinganddeserializinganobject.
ObjectOutputStreamhasmanymethodforserializingobjectbutcommonlyusedmethodis:

1
2
3
4

privatevoidwriteObject(ObjectOutputStreamos)throwsIOException
{

SimilarlyObjectInputStreamhas
1
2
3
4

privatevoidreadObject(ObjectInputStreamis)throwsIOException,ClassNotFoundException
{

NeedofSerialization?
SerializationisusuallyusedWhentheneedarisestosendyourdataovernetworkorstoredinfiles.BydataImeanobjectsandnottext.Now
theproblemisyourNetworkinfrastructureandyourHarddiskarehardwarecomponentsthatunderstandbitsandbytesbutnotJavaobjects.
SerializationisthetranslationofyourJavaobjectsvalues/statestobytestosenditovernetworkorsaveit.Onotherhand,Deserializationis
conversionofbytecodetocorrespondingjavaobjects.

ConceptofserialVersionUID:
SerialVersionUIDisusedtoensurethatsameobject(ThatwasusedduringSerialization)isloadedduringDeserialization.serialVersionUIDis
usedforversioncontrolofobject.YoucanreadmoreatserialVersionUIDinjavaserialization

ForSerialization:
Stepsare:

http://www.javacodegeeks.com/2013/03/serializationinjava.html

weeklyupdatesandcomplimentary
whitepapers!

Jointhemnowtogain
accesstothelatestnewsintheJava

aswellasinsightsaboutAndroid,Scala,
Groovyandotherrelatedtechnologies.

Emailaddress:
Youremailaddress
Signup

JOIN US

With 1,240,600
uniquevisitorsand
500 authorswe
placedamongthe
relatedsitesaroun
Constantlybeingo
lookoutforpartne
encourageyouto
SoIfyouhaveab
uniqueandinterestingcontentthenyoush
checkoutourJCGpartnersprogram.You
beaguestwriterforJavaCodeGeeksa
yourwritingskills!

CAREER OPPORTUNITIES
what:
title,keywords

where:
city,state,orzip

FindJobs

1/13

29/8/2015

Serializationinjava

Letstakeanexample:CreateEmployee.javainsrc>org.arpit.javapostsforlearning:

1.Employee.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

packageorg.arpit.javapostsforlearning;
importjava.io.Serializable;
publicclassEmployeeimplementsSerializable{

intemployeeId;
StringemployeeName;
Stringdepartment;

publicintgetEmployeeId(){
returnemployeeId;
}
publicvoidsetEmployeeId(intemployeeId){
this.employeeId=employeeId;
}
publicStringgetEmployeeName(){
returnemployeeName;
}
publicvoidsetEmployeeName(StringemployeeName){
this.employeeName=employeeName;
}
publicStringgetDepartment(){
returndepartment;
}
publicvoidsetDepartment(Stringdepartment){
this.department=department;
}
}

Asyoucanseeabove,ifyouwanttoserializeanyclassthenitmustimplementSerializableinterfacewhichismarkerinterface.
MarkerinterfaceinJavaisinterfaceswithnofieldormethodsorinsimplewordemptyinterfaceinjavaiscalledmarkerinterface.Create
SerializeMain.javainsrc>org.arpit.javapostsforlearning

2.SerializeMain.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

packageorg.arpit.javapostsforlearning;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectOutputStream;
publicclassSerializeMain{

/**
*@authorArpitMandliya
*/
publicstaticvoidmain(String[]args){

Employeeemp=newEmployee();
emp.setEmployeeId(101);
emp.setEmployeeName('Arpit');
emp.setDepartment('CS');
try
{
FileOutputStreamfileOut=newFileOutputStream('employee.ser');
ObjectOutputStreamoutStream=newObjectOutputStream(fileOut);
outStream.writeObject(emp);
outStream.close();
fileOut.close();
}catch(IOExceptioni)
{
i.printStackTrace();
}
}
}

ForDeserialization:
Stepsare:

http://www.javacodegeeks.com/2013/03/serializationinjava.html

2/13

29/8/2015

Serializationinjava

CreateDeserializeMain.javainsrc>org.arpit.javapostsforlearning

3.DeserializeMain.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

packageorg.arpit.javapostsforlearning;
importjava.io.IOException;
importjava.io.ObjectInputStream;

publicclassDeserializeMain{
/**
*@authorArpitMandliya
*/
publicstaticvoidmain(String[]args){

Employeeemp=null;
try
{
FileInputStreamfileIn=newFileInputStream('employee.ser');
ObjectInputStreamin=newObjectInputStream(fileIn);
emp=(Employee)in.readObject();
in.close();
fileIn.close();
}catch(IOExceptioni)
{
i.printStackTrace();
return;
}catch(ClassNotFoundExceptionc)
{
System.out.println('Employeeclassnotfound');
c.printStackTrace();
return;
}
System.out.println('DeserializedEmployee...');
System.out.println('Empid:'+emp.getEmployeeId());
System.out.println('Name:'+emp.getEmployeeName());
System.out.println('Department:'+emp.getDepartment());
}
}

4.Runit:
FirstrunSerializeMain.javathenDeserializeMain.javaandyouwillgetfollowingoutput:
1
2
3
4

DeserializedEmployee...
Empid:101
Name:Arpit
Department:CS

Sowehaveserializeanemployeeobjectandthendeserializedit.Itseemsverysimplebutitcanbeverycomplexwhenreference
object,inheritancecomeintothepicture.Sowewillseedifferentcasesonebyoneandhowwecanapplyserializationindifferentscenarios.

Case1Whatifanobjecthasareferencetootherobjects
Wehaveseenverysimplecaseofserialization,nowwhatifitalsoareferencetootherobjects.Howwillitserializedthen?willreferenceobject
willalsogetserialized?.Yes,Youdonthavetoexplicitlyserializereferenceobjects.Whenyouserializeanyobjectandifitcontainanyother
objectreferencethenJavaserializationserializethatobjectsentireobjectgraph.
Forexample:Letssay,EmployeenowhasreferencetoaddressobjectandAddresscanhavereferencetosomeotherobject(e.g.Home)then
whenyouserializeEmployeeobjectallotherreferenceobjectssuchasaddressandhomewillbeautomaticallyserialized.LetscreateAddress
classandaddobjectofAddressasareferencetoaboveemployeeclass.

Employee.java:
01
02
03
04
05
06
07
08
09
10
11
12

packageorg.arpit.javapostsforlearning;
importjava.io.Serializable;

publicclassEmployeeimplementsSerializable{

intemployeeId;
StringemployeeName;
Stringdepartment;
Addressaddress;

publicintgetEmployeeId(){
returnemployeeId;

http://www.javacodegeeks.com/2013/03/serializationinjava.html

3/13

29/8/2015

Serializationinjava

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

}
publicvoidsetEmployeeId(intemployeeId){
this.employeeId=employeeId;
}
publicStringgetEmployeeName(){
returnemployeeName;
}
publicvoidsetEmployeeName(StringemployeeName){
this.employeeName=employeeName;
}
publicStringgetDepartment(){
returndepartment;
}
publicvoidsetDepartment(Stringdepartment){
this.department=department;
}
publicAddressgetAddress(){
returnaddress;
}
publicvoidsetAddress(Addressaddress){
this.address=address;
}
}

CreateAddress.javainorg.arpit.javapostsforlearning:

Address.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

packageorg.arpit.javapostsforlearning;
publicclassAddress{

inthomeNo;
Stringstreet;
Stringcity;
publicAddress(inthomeNo,Stringstreet,Stringcity){
super();
this.homeNo=homeNo;
this.street=street;
this.city=city;
}
publicintgetHomeNo(){
returnhomeNo;
}
publicvoidsetHomeNo(inthomeNo){
this.homeNo=homeNo;
}
publicStringgetStreet(){
returnstreet;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicStringgetCity(){
returncity;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
}

CreateSerializeDeserializeMain.javainorg.arpit.javapostsforlearning:

SerializeDeserializeMain.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

packageorg.arpit.javapostsforlearning;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;

publicclassSerializeDeserializeMain{
/**
*@authorArpitMandliya
*/
publicstaticvoidmain(String[]args){

Employeeemp=newEmployee();
emp.setEmployeeId(101);
emp.setEmployeeName('Arpit');
emp.setDepartment('CS');
Addressaddress=newAddress(88,'MGroad','Pune');
emp.setAddress(address);
//Serialize
try
{
FileOutputStreamfileOut=newFileOutputStream('employee.ser');
ObjectOutputStreamoutStream=newObjectOutputStream(fileOut);
outStream.writeObject(emp);
outStream.close();
fileOut.close();
}catch(IOExceptioni)
{
i.printStackTrace();
}

http://www.javacodegeeks.com/2013/03/serializationinjava.html

4/13

29/8/2015

Serializationinjava

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

//Deserialize
emp=null;
try
{
FileInputStreamfileIn=newFileInputStream('employee.ser');
ObjectInputStreamin=newObjectInputStream(fileIn);
emp=(Employee)in.readObject();
in.close();
fileIn.close();
}catch(IOExceptioni)
{
i.printStackTrace();
return;
}catch(ClassNotFoundExceptionc)
{
System.out.println('Employeeclassnotfound');
c.printStackTrace();
return;
}
System.out.println('DeserializedEmployee...');
System.out.println('Empid:'+emp.getEmployeeId());
System.out.println('Name:'+emp.getEmployeeName());
System.out.println('Department:'+emp.getDepartment());
address=emp.getAddress();
System.out.println('City:'+address.getCity());
}
}

Runit:
WhenyourunSerializeDeserializeMain.java.Youwillgetfollowingoutput:
1
2
3
4
5
6
7

java.io.NotSerializableException:org.arpit.javapostsforlearning.Address
atjava.io.ObjectOutputStream.writeObject0(UnknownSource)
atjava.io.ObjectOutputStream.defaultWriteFields(UnknownSource)
atjava.io.ObjectOutputStream.writeSerialData(UnknownSource)
atjava.io.ObjectOutputStream.writeOrdinaryObject(UnknownSource)
atjava.io.ObjectOutputStream.writeObject0(UnknownSource)
atjava.io.ObjectOutputStream.writeObject(UnknownSource)

Wegotexceptionwhatwentwrong.Iforgottomention,Addressclassmustalsobeserializable.SoyouhavetomakeAddressserializableby
implementserialzableinterface.

Address.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

importjava.io.Serializable;

publicclassAddressimplementsSerializable{

inthomeNo;
Stringstreet;
Stringcity;
publicAddress(inthomeNo,Stringstreet,Stringcity){
super();
this.homeNo=homeNo;
this.street=street;
this.city=city;
}
publicintgetHomeNo(){
returnhomeNo;
}
publicvoidsetHomeNo(inthomeNo){
this.homeNo=homeNo;
}
publicStringgetStreet(){
returnstreet;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicStringgetCity(){
returncity;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
}

Runagain:
WhenyourunagainSerializeDeserializeMain.java.Youwillgetfollowingoutput:
1
2
3
4
5

DeserializedEmployee...
Empid:101
Name:Arpit
Department:CS
City:Pune

Case2:Whatifyoudonthaveaccesstoreferenceobjects
sourcecode(e.gyoudonthaveaccesstoaboveAddress
http://www.javacodegeeks.com/2013/03/serializationinjava.html

5/13

29/8/2015

Serializationinjava

class)
IfyoudonthaveaccesstoaddressclassthenhowwillyouimplementserializableinterfaceinAddressclass.Isthereanyalternativetothat?
yesthereis,YoucancreateanotherclasswhichextendsaddressandmakeitserialzablebutItcanfailsinmanycases:
Whatifclassisdeclaredasfinal
Whatifclasshavereferencetoothernonserializableobject.
SothenhowwillyouserializeEmployeeobject?sosolutionisyoucanmakeittransient.Ifyoudontwanttoserializeanyfieldthenmakeit
transient.
1 transientAddressaddress
SoaftermakingaddresstransientinEmployeeclasswhenyourunprogram.YouwillgetnullPointerExceptionbecauseduringdeserialization
addressreferencewillbenull

Case3:Whatifyoustillwanttosavestateofreference
object(e.gaboveaddressobject):
Ifyoumakeaddresstransientthenduringdeserializationitwillreturnnull.Butwhatifyoustillwanttohavesamestateaswhenyouhave
serializedaddressobject.Javaserializationprovidesamechnismsuchthatifyouhaveprivatemethodswithparticularsignaturethentheywill
getcalledduringserializationanddeserializationsowewilloverridewriteObjectandreadObjectmethodofemployeeclassandtheywillbe
calledduringserializationanddeserializationofEmployeeobject.

Employee.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

packageorg.arpit.javapostsforlearning;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.io.Serializable;

publicclassEmployeeimplementsSerializable{

intemployeeId;
StringemployeeName;
Stringdepartment;
transientAddressaddress;

publicintgetEmployeeId(){
returnemployeeId;
}
publicvoidsetEmployeeId(intemployeeId){
this.employeeId=employeeId;
}
publicStringgetEmployeeName(){
returnemployeeName;
}
publicvoidsetEmployeeName(StringemployeeName){
this.employeeName=employeeName;
}
publicStringgetDepartment(){
returndepartment;
}
publicvoidsetDepartment(Stringdepartment){
this.department=department;
}
publicAddressgetAddress(){
returnaddress;
}
publicvoidsetAddress(Addressaddress){
this.address=address;
}

privatevoidwriteObject(ObjectOutputStreamos)throwsIOException,ClassNotFoundException
{
try{
os.defaultWriteObject();
os.writeInt(address.getHomeNo());
os.writeObject(address.getStreet());
os.writeObject(address.getCity());
}
catch(Exceptione)
{e.printStackTrace();}
}

privatevoidreadObject(ObjectInputStreamis)throwsIOException,ClassNotFoundException
{
try{
is.defaultReadObject();
inthomeNo=is.readInt();
Stringstreet=(String)is.readObject();
Stringcity=(String)is.readObject();
address=newAddress(homeNo,street,city);

}catch(Exceptione){e.printStackTrace();}
}
}

OnethingshouldbekeptinmindthatObjectInputStreamshouldreaddatainsamesequenceinwhichwehavewrittendatato
ObjectOutputStream.CreateAddress.javainorg.arpit.javapostsforlearning:

Address.java:
01 packageorg.arpit.javapostsforlearning;
02 importjava.io.Serializable;

http://www.javacodegeeks.com/2013/03/serializationinjava.html

6/13

29/8/2015

Serializationinjava

03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

publicclassAddress{

inthomeNo;
Stringstreet;
Stringcity;

publicAddress(inthomeNo,Stringstreet,Stringcity){
super();
this.homeNo=homeNo;
this.street=street;
this.city=city;
}
publicintgetHomeNo(){
returnhomeNo;
}
publicvoidsetHomeNo(inthomeNo){
this.homeNo=homeNo;
}
publicStringgetStreet(){
returnstreet;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicStringgetCity(){
returncity;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
}

CreateSerializeDeserializeMain.javainorg.arpit.javapostsforlearning:

SerializeDeserializeMain.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

packageorg.arpit.javapostsforlearning;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;

publicclassSerializeDeserializeMain{
/**
*@authorArpitMandliya
*/
publicstaticvoidmain(String[]args){

Employeeemp=newEmployee();
emp.setEmployeeId(101);
emp.setEmployeeName('Arpit');
emp.setDepartment('CS');
Addressaddress=newAddress(88,'MGroad','Pune');
emp.setAddress(address);
//Serialize
try
{
FileOutputStreamfileOut=newFileOutputStream('employee.ser');
ObjectOutputStreamoutStream=newObjectOutputStream(fileOut);
outStream.writeObject(emp);
outStream.close();
fileOut.close();
}catch(IOExceptioni)
{
i.printStackTrace();
}

//Deserialize
emp=null;
try
{
FileInputStreamfileIn=newFileInputStream('employee.ser');
ObjectInputStreamin=newObjectInputStream(fileIn);
emp=(Employee)in.readObject();
in.close();
fileIn.close();
}catch(IOExceptioni)
{
i.printStackTrace();
return;
}catch(ClassNotFoundExceptionc)
{
System.out.println('Employeeclassnotfound');

c.printStackTrace();
return;
}
System.out.println('DeserializedEmployee...');
System.out.println('Empid:'+emp.getEmployeeId());
System.out.println('Name:'+emp.getEmployeeName());
System.out.println('Department:'+emp.getDepartment());
address=emp.getAddress();
System.out.println('City:'+address.getCity());
}
}

Runit:
WhenyourunSerializeDeserializeMain.java.Youwillgetfollowingoutput:
1
2
3
4
5

DeserializedEmployee...
Empid:101
Name:Arpit
Department:CS
City:Pune

http://www.javacodegeeks.com/2013/03/serializationinjava.html

7/13

29/8/2015

Serializationinjava

sonowwegotsamestateofaddressobjectasitwasbeforeserialization.

InheritanceinSerialization:
Nowwewillseehowinheritanceaffectsserialization.Sotherecanbemuliplecaseswhethersuperclassisserializableornot.Ifnotthenhow
willyouhandlethatandhowitworks.Letsseebyexample.WewillcreatePerson.javawhichwillbesuperclassofEmployee:

Case4:WhatifsuperclassisSerializable?
Ifsuperclassisserialzablethenallitssubclassesareautomaticallyserializable.

Case5:WhatifsuperclassisnotSerializable?
Ifsuperclassisnotserializablethenwehavetohandleitquitedifferently.
Ifsuperclassisnotserializablethenitmusthavenoargumentconstructor.
Person.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

packageorg.arpit.javapostsforlearning;
publicclassPerson{

Stringname='default';
Stringnationality;

publicPerson()
{
System.out.println('Person:Constructor');
}

publicPerson(Stringname,Stringnationality){
super();
this.name=name;
this.nationality=nationality;
}

publicStringgetName(){
returnname;
}

publicvoidsetName(Stringname){
this.name=name;
}

publicStringgetNationality(){
returnnationality;
}

publicvoidsetNationality(Stringnationality){
this.nationality=nationality;
}

CreateEmployee.javainorg.arpit.javapostsforlearning:

Employee.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

packageorg.arpit.javapostsforlearning;
importjava.io.Serializable;

publicclassEmployeeextendsPersonimplementsSerializable{

intemployeeId;
Stringdepartment;

publicEmployee(intemployeeId,Stringname,Stringdepartment,Stringnationality)
{
super(name,nationality);
this.employeeId=employeeId;
this.department=department;
System.out.println('Employee:Constructor');
}

publicintgetEmployeeId(){
returnemployeeId;
}
publicvoidsetEmployeeId(intemployeeId){
this.employeeId=employeeId;
}

http://www.javacodegeeks.com/2013/03/serializationinjava.html

8/13

29/8/2015
23
24
25
26
27
28
29
30

Serializationinjava

publicStringgetDepartment(){
returndepartment;
}
publicvoidsetDepartment(Stringdepartment){
this.department=department;
}
}

CreateSerializeDeserializeMain.javainorg.arpit.javapostsforlearning:

SerializeDeserializeMain.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

packageorg.arpit.javapostsforlearning;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;

publicclassSerializeDeserializeMain{

/**
*@authorArpitMandliya
*/
publicstaticvoidmain(String[]args){

//Serialize
Employeeemp=newEmployee(101,'Arpit','CS','Indian');
System.out.println('Beforeserializing');
System.out.println('Empid:'+emp.getEmployeeId());
System.out.println('Name:'+emp.getName());
System.out.println('Department:'+emp.getDepartment());
System.out.println('Nationality:'+emp.getNationality());
System.out.println('************');
System.out.println('Serializing');
try
{
FileOutputStreamfileOut=newFileOutputStream('employee.ser');
ObjectOutputStreamoutStream=newObjectOutputStream(fileOut);
outStream.writeObject(emp);
outStream.close();
fileOut.close();
}catch(IOExceptioni)
{
i.printStackTrace();
}

//Deserialize
System.out.println('************');
System.out.println('Deserializing');
emp=null;
try
{
FileInputStreamfileIn=newFileInputStream('employee.ser');
ObjectInputStreamin=newObjectInputStream(fileIn);
emp=(Employee)in.readObject();
in.close();
fileIn.close();
}catch(IOExceptioni)
{
i.printStackTrace();
return;
}catch(ClassNotFoundExceptionc)
{
System.out.println('Employeeclassnotfound');
c.printStackTrace();
return;
}
System.out.println('Afterserializing');
System.out.println('Empid:'+emp.getEmployeeId());
System.out.println('Name:'+emp.getName());
System.out.println('Department:'+emp.getDepartment());
System.out.println('Nationality:'+emp.getNationality());
}
}

Runit:
WhenyourunSerializeDeserializeMain.java.Youwillgetfollowingoutput:

http://www.javacodegeeks.com/2013/03/serializationinjava.html

9/13

29/8/2015

Serializationinjava

IfsuperclassisnotSerializablethenallvaluesoftheinstancevariablesinheritedfromsuperclasswillbeinitializedbycallingconstructorof
NonSerializableSuperclassduringdeserializationprocess.Soherenameisinheritedfrompersonsoduringdeserialization,nameisinitialized
todefault.

Case6WhatifsuperclassisSerializablebutyoudontwant
subclasstobeSerializable
IfyoudontwantsubclasstoserializablethenyouneedtoimplementwriteObject()andreadObject()methodandneedtothrow
NotSerializableExceptionfromthismethods.

Case7CanyouSerializestaticvariables?
No,youcant.Asyouknowstaticvariableareatclasslevelnotatobjectlevelandyouserializeaobjectsoyoucantserializestaticvariables.

Summary:
SerializationisthetranslationofyourJavaobjectsvalues/statestobytestosenditovernetworkorsaveit.Onotherhand,Deserializationis
conversionofbytecodetocorrespondingjavaobjects.
GoodthingaboutSerializationisentireprocessisJVMindependent,meaninganobjectcanbeserializedononeplatformanddeserialized
onanentirelydifferentplatform.\
IfyouwanttoserializeanyclassthenitmustimplementSerializableinterfacewhichismarkerinterface.
MarkerinterfaceinJavaisinterfacewithnofieldormethodsorinsimplewordemptyinterfaceinjavaiscalledmarkerinterface
serialVersionUIDisusedtoensurethatsameobject(ThatwasusedduringSerialization)isloadedduringDeserialization.serialVersionUID
isusedforversioncontrolofobject.
WhenyouserializeanyobjectandifitcontainanyotherobjectreferencethenJavaserializationserializethatobjectsentireobjectgraph.
Ifyoudontwanttoserializeanyfield,thenmakeittrasient.
IfsuperclassisSerializablethenitssubclassesareautomaticallySerializable.
IfsuperclassisnotSerializablethenallvaluesoftheinstancevariablesinheritedfromsuperclasswillbeinitializedbycallingconstructorof
NonSerializableSuperclassduringdeserializationprocess.
IfyoudontwantsubclasstoserializablethenyouneedtoimplementwriteObject()andreadObject()methodandneedtothrow
NotSerializableExceptionfromthismethods.
Youcantserializestaticvariables.

Reference:SerializationinjavafromourJCGpartnerArpitMandliyaattheJavaframeworksanddesignpatternsforbeginners
blog.

Taggedwith:

SERIALIZATION

DoyouwanttoknowhowtodevelopyourskillsettobecomeaJava
Rockstar?
SubscribetoournewslettertostartRockingrightnow!
TogetyoustartedwegiveyouourbestsellingeBooksforFREE!
1.JPAMiniBook
2.JVMTroubleshootingGuide
3.JUnitTutorialforUnitTesting
4.JavaAnnotationsTutorial
5.JavaInterviewQuestions
6.SpringInterviewQuestions
7.AndroidUIDesign
andmanymore....

Emailaddress:
Youremailaddress
Signup

13 COMMENTS
AbhijeetRai
October25th,2013at2:03pm

ExcellentpostArpit!!Itstooverbose,infact.Canyoupleaseelaboratethecase3.WhenexactlythewriteObject/readObjectmethods
arecalled.Because,weareassumingthatwehaveonlyonetransientvariableAddress.Whatifwehavesomeothertransientvariable
saySupervisor(intempId,Stringname).?HowwillweserializetheEmployeeobject.Thanksinadvance.

http://www.javacodegeeks.com/2013/03/serializationinjava.html

10/13

29/8/2015

Serializationinjava
Reply

Rajeshhalder
November23rd,2013at8:27pm

thankyouitwasveryhelpful.afterlongtimeibecameabletounderstandabouttheserializationandallofthat.thanksones
more
Reply

NitinRamachandra
October27th,2014at6:11pm

Kudosman..!!!!Youvedoneagreatjobbyspecifyingcertainthingsinaveryprecisemanner.Aonestopforallthenecessary
informationonSerializationinJava..!!!
Reply

JAVA
October29th,2014at10:58am

Awesomepost!!!!!
Reply

ChetanPatel
December17th,2014at2:22pm

verynicelyexplained,bravo.
Reply

DilipSinghVirk
January4th,2015at2:16pm

Hi,
Youexplainedverywellaboutserializationprocessinjavaitjustclearedmydouts.
Thanks
Reply

Akash
February20th,2015at9:53am

HiArpit,
Indeedexcellentpost,HoweverImstillnotabletofindtheanswerwhichanintervieweraskedtome(relatedtoJavaSerialization)and
Icouldntconvincehim.Ivesearchedmanyblogsbutnotgettinganyleads.
IntervieweraskedmeLetsayyouhaveaEmployeeclasshaving3properties(name,company,salary)wheresalaryistransient
variable.WhenyouserializeEmployeeobject,salarywillnotbestoredintoserializedfilewhichcanbeevidentbyinspectingthefile
(althoughthecontentofthefilewillbebinarybutyoucanseeseethepropertynameinsideitandsurelyyouwontseesalarythere).
NowwhenyoudeserializedthisEmployeeobjectbackandtrytogetthevalueofname,companyandsalaryyouwillgetthenullvalue
forsalaryasexpected.Myquestionishowyoucanevenrefertheattribute(e.g.salary)whichwasnotthereinserializedfile,Asthere
wasnoexistenceofsalaryfieldinreturnedemployeeobjectduringdeserializationprocesssodontyouthinkyoushouldget
NullPointerExceptionratherthanNull?
ThoughIwasprettyconfidentthattransientfieldnevergetstoredandtryingtogetthevalueofthisvalueindeserializedobjectwill
returnnullbutIwasnotabletologicallyanswerwhyitshouldntgiveNullPointerExceptionrathernullvalue.
IamsureImmissingsomethingbutnotabletogetwhereImwrong:(
Reply

Venkitesh
June18th,2015at8:32pm

WhatIunderstoodisthatyouareserializingthewholeobjectwithaconditionthatthetransientvariablesvalueshouldnotbe
takenwith.Thatsthereasonwhywegetanull.ButIdontknowwhyyouthoughtthatthereshouldbeanullpointerexception
thatshouldcomeup.Becausewhiledeserialization,yougettheemployeeobjectwhichisnotnull.Soadotoperatoronanon
nullobjectwillnotdefinitelygiveyouanullpointerexception.
Eg:udeserializetheobjecttogetEmployeeempwhichisnotnull.
emp.getsalaryoremp.getnameorwhateverwillnotgiveuanullpointeraspermyunderstanding.
Reply

kdj
March9th,2015at5:58pm

everyexampleofserializingistoafile.iwanttoserializemyobject(implementsserializable)toaString.(pleasedontaskwhyor
offeralternatives)Idonthaveaccesstothetostringcodefortheobject.
Cananyonepostexamplecodeforthis??
Reply

http://www.javacodegeeks.com/2013/03/serializationinjava.html

11/13

29/8/2015

Serializationinjava
raji
May1st,2015at6:05am

IbelievetheCase1isNOTtrue.TheAddressshouldimplementserializableinordertoserializetheEmployeeobj.Itesteditinmy
machine.
Reply

Venkitesh
June18th,2015at8:24pm

Right..Theexamplealreadysaysthat.Buteitherthedescriptionofcase1orexamplehasgonewrong.
Reply

Venkitesh
June18th,2015at8:22pm

YesTheabovesaidcommentistrue.Boththecase1descriptionandtheexamplecontradictstoeachother.
Couldyoumakeitclearandcorrect?
Anywayawonderfuleffort.
Reply

pramodvidyagar
July16th,2015at4:13pm

HI,
ThatsaverynicedocumentonSerialization.
PleaseaddwriteReplaceandreadResolvemethodsalsotomakeitcomplete.
Reply

LEAVE A REPLY
Youremailaddresswillnotbepublished.Requiredfieldsaremarked*
Name*

Email*

Website

=fiftyfour

PostComment

Notifymeoffollowupcommentsviaemail.Youcanalsosubscribewithoutcommenting.
Signmeupforthenewsletter!

KNOWLEDGE BASE

HALL OF FAME

Academy

AndroidFullApplicationTutorialseries

Examples

11OnlineLearningwebsitesthatyou
shouldcheckout

Library
Resources
Tutorials
Whitepapers

AdvantagesandDisadvantagesofCloud
ComputingCloudcomputingprosand
cons
AndroidGoogleMapsTutorial
AndroidJSONParsingwithGsonTutorial

PARTNERS
Mkyong

AndroidLocationBasedServices
ApplicationGPSlocation

ABOUT JAVA CODE GEEKS

JCGs(JavaCodeGeeks)isanindependentonlinecommunityfocusedoncreating
ultimateJavatoJavadevelopersresourcecentertargetedatthetechnicalarchite
technicalteamlead(seniordeveloper),projectmanagerandjuniordevelopersali
JCGsservetheJava,SOA,AgileandTelecomcommunitieswithdailynewswritten
domainexperts,articles,tutorials,reviews,announcements,codesnippetsandop
sourceprojects.

DISCLAIMER

AlltrademarksandregisteredtrademarksappearingonExamplesJavaCodeGeek
thepropertyoftheirrespectiveowners.Javaisatrademarkorregisteredtradem
OracleCorporationintheUnitedStatesandothercountries.ExamplesJavaCode
isnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation

AndroidQuickPreferencesTutorial

http://www.javacodegeeks.com/2013/03/serializationinjava.html

12/13

29/8/2015

THE CODE GEEKS NETWORK


.NETCodeGeeks
JavaCodeGeeks
WebCodeGeeks

Serializationinjava
DifferencebetweenComparatorand
ComparableinJava
GWT2Spring3JPA2Hibernate3.5
Tutorial
JavaBestPracticesVectorvsArrayList
vsHashSet

JavaCodeGeeksandallcontentcopyright20102015,ExelixisMediaP.C.|TermsofUse|PrivacyPolicy|Contact

http://www.javacodegeeks.com/2013/03/serializationinjava.html

13/13

Вам также может понравиться