Serializing object is a good feature i am sure you have heard in somewhere.It is actually about fields of the object and saving them for later use.Suppose you have a class Shape that have two instance variable named as width and height of integer type.When you serialize them you actually saving their state , and then de-serialize to their orginal state(by orginal state not to mean first state when class created , state that variables have before they go into serialization process).Of course to make them serializable you have to use Serializable ınterface.Serializable interface actually different from other kinds of interfaces cause it has no method at all to implement, it just give you the ability to froze state of the object fields and save them and later you can use them for your purposes.When implement serializable interface with class it means that instance variables of that class can save their state.
And What Happen if class not only have primitive field variables also reference variables?
Actually it doesnt change so much thing you have reference to and object in your class as instance variable after serializing object you serializing all the objects that reference refer.So you actually serialize all the object in reference tree.
What Happen if There is a Problem While Serializing Object?
While you serialize all the object in reference tree (mean all the objects that connect each other with references) suppose there is a problem and one of the object serializing process blow up.Then what happen?Does it mean object come with different value back?No .Serializing is “to be or not to be” style process when one of the process blow up all the process blow up other way you have wrong value of the object.Enough background info lets give some example how to read and write object state.Suppose you have 3 objects first,second and third you want to save their state into file like “Game.sv”.Here is what you do…
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(“Game.sv”) );
os.writeObject(first);
os.writeObject(second);
os.writeObject(third);
os.close()
Let me explain what happening here.You first give chain to FileOutputStream to help the ObjectOutputStream cause object output stream doesnt have clue about how to handle file.The real job here is object output stream write objects by the help of the file output stream.
What happen while de-serializing the objects(means reading from )?
Actually this is the detailed process of the JVM but it is good to know what happening behind.First of all when you reads objects you get the same state while you serailize them.But how?Simple JVM create object that has exactly same state with the object that serialized.So when reading with object input stream you get object as return value.Lets see a example of it.
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(“Game.sv”));
GameChar firstAfter=(GameChar)ois.readObject();
GameChar secondAfter=(GameChar)ois.readObject();
GameChar thirdAfter=(GameChar)ois.readObject();
//read all objects state back
System.out.println(“First Charater Type was : “+firstAfter.getType());
System.out.println(“Second Character Type was: “+secondAfter.getType());
System.out.println(“Third Character Type was: “+thirdAfter.getType());
Here is you again use object stream but this time input stream and also with file stream.You give the same file name to the program and read in order that you put them.(this is very important).And also if you read more then object you put you get exception error.And print to see if it works corret.I will give complete code below.
This time you can have some question in your mind.Why not we are serailizing hole class?
This is not a good idea in object oriented programming and it is also big overhead.In objects the important and different parts are the fields of that object by serializing hole class you actually holding unnecessary parts of the object,first it seems good but think that you transfering these object through the network and sending hole class will kill the bandwith if you sending a lot object.That why only important part or unique parts of the object is serailizing.Here is the complete code for you to understand suppose you are in rpg game and you want to save your characters (i think it is a best example from real life)
——————————————–Here is the GameChar class——————————————
package com.serial.object;
import java.io.Serializable;
public class GameChar implements Serializable{
/*
* this is a clas that hold the game characters
* properties implements serializable interface
* to save the fields of this class’s object
*/
int power;
//hold the power
String type;
//hold type of the character
String [] weapons;
//hold the weapons of the character
public GameChar(int power,String type,String [] weapons){
/*
* 3 argument constructor for
* class
*/
this.power=power;
this.type=type;
this.weapons=weapons;
}
/**
* @return the power
*/
public int getPower() {
return power;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @return the weapons
*/
public String getWeapons() {
String temp=”";
//get the all weapons into string object
for (int i = 0; i < weapons.length; i++) {
temp+=weapons[i]+” “;
}
return temp;
}
}
—————————————-Here is the GameSave class————————————————-
package com.serial.object;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.sun.corba.se.impl.orbutil.ObjectWriter;
public class GameSave {
/*
* this class is to test if game objects
* fields can be serializable or not
* just test class
*/
public static void main(String[] args) throws ClassNotFoundException {
GameChar first=new GameChar(50,”Elf”,new String [] {“bow”,”sword”,”dust” });
GameChar second=new GameChar(200,”Troll”, new String [] {“bare hand”,”big ax”});
GameChar third=new GameChar(120,”Magician”,new String [] {“spells”,”invisiblity”});
//game chars objects
// now write the objects state to system so that
//user can start where it left
try{
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(“Game.sv”) );
os.writeObject(first);
os.writeObject(second);
os.writeObject(third);
os.close();
}catch(IOException e) {
e.printStackTrace();
//print if problem happen while input or output
}
first=null;
second=null;
third=null;
//make them null to not access objects
//lets read object and see if they still got the last values
try{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(“Game.sv”));
GameChar firstAfter=(GameChar)ois.readObject();
GameChar secondAfter=(GameChar)ois.readObject();
GameChar thirdAfter=(GameChar)ois.readObject();
//read all objects state back
System.out.println(“First Charater Type was : “+firstAfter.getType());
System.out.println(“Second Character Type was: “+secondAfter.getType());
System.out.println(“Third Character Type was: “+thirdAfter.getType());
ois.close();
}catch(IOException ex){
ex.printStackTrace();
//print if problem happens while input ot output
}
}
}
Burak DEDE
Son Yorumlar