CS202 - Chapter 6 - Serialization
CS202 - Chapter 6 - Serialization
CHAPTER 5
SERIALIZATION IN JAVA
SOPHOMORE SE/HEC
SPRING 2024
2. Serialization in Java
Agenda
3. Binary serialization
4. XML serialization
Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist the object.
After a serialized object has been written into a file, it can be read from that file and then
deserialized, ie. the type information and bytes represented by that object and then, its data
can be used to recreate the object in memory.
synonymous
▪ Marshalling / Unmarshalling
▪ Sometimes linearization
thus, attributes instantiating other classes must also implement the same interface
Serializable
The structure of an object must be kept to reconstruct the object during the
deserialization task (Example : arrays, lists , etc.)
// attributes
private String fname, lname ;
Handling events
▪ Opening and Reading objects / arrays, writning values, closing objects
▪ Structures outside memory, serial access
▪ Styles of reading API :
• Pushing reminding callback functions
• Pulling by event iterators
Exceptions:
▪▪ FileNotFoundException → when the file is not available (found)
▪▪ ClassNotFoundException → when the class is not found, defined, etc.
▪▪ InvalidClassException → problem with the class versions
▪▪ ObjectStreamException → distorted file
▪▪ Check serialized objects thanks to ObjectInputValidation → the method validateObject() checks the
object and may throw an InvalidObjectException in case of problems
import java.io.*;
public class Person implements Serializable {
private String name;
int age;
private static final long serialVersionUID=1;
public Person (String _name, int _age)
{ this.name = _name;
this.age = _age; }
public String toString(){
return (name +", "+age);
}
}
2/26/2024 CS202 - ADVANCED OOP 20
Object storage using files in Java
Reading objects
▪▪ Class ObjectInputStream
o Method Object readObject()
o We should add a casting operation for the objects to be retreived
import java.io.*;
public class Dog implements Serializable{
private String name;
while(nbP>0){
p=(Person)ois.readObject();
System.out.println(p.toString());
nbP-‐-‐; }
ois.close();
fi.close(); }
catch(Exception e)
{ e.printStackTrace(); } } }
◦ XMLDecoder
public DVD(){}
}
}