Avoid Subclass serialization when super is serialized:
To prevent subclass from being serialized we must
implement writeObject() and readObject() method and need to throw
NotSerializableException from these methods.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Human implements Serializable {
private static final long serialVersionUID = 1L;
String
gender;
Human(String
gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
class Man extends Human {
private String name;
Man(String
gender, String name) {
super(gender);
this.name = name;
}
private void readObject(java.io.ObjectInputStream stream) {
try {
throw new NotSerializableException();
}
catch (NotSerializableException e) {
}
}
private void writeObject(java.io.ObjectOutputStream stream) {
try {
throw new NotSerializableException();
}
catch (NotSerializableException e) {
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Implementation {
public static void main(String args[]) {
/* Assigning values to Man class's
instance.*/
Man
man = new Man("Male", "Andrew");
/* Serializing Man's instance.*/
try {
FileOutputStream
fileOutputStream =
new FileOutputStream("serialObject.ser");
ObjectOutputStream
objectOutputStream =
new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(man);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
/* Deserializing Man's instance. */
Man
manout = null;
try {
FileInputStream
fileInputStream =
new FileInputStream("serialobject.ser");
ObjectInputStream
inputStream =
new ObjectInputStream(fileInputStream);
manout = (Man) inputStream.readObject();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
}
/*
* Printing values from deserialized Man's
object
*/
System.out.println("Value of Deserailized instance
:");
System.out.println("Gender: " + manout.getGender());
System.out.println("Name: " + manout.getName());
}
}
Output:
Value of Deserailized
instance :
Gender: Male
Name: null
Output: commenting the readObject and writeObject
methods.
Value of Deserailized
instance :
Gender: Male
Name: Andrew
No comments:
Post a Comment