How to Prevent Child class from Serialization in Java

8 08 2014

We have parent class which is serializable, but child class we should not allow serializable. for this we can writeObject,readObject API’s throw NotSerializableException Exception in Child Class.

1) Parent Class

public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
public String name;
public String address;
}

2) Child Class

public class Child extends Parent implements Serializable {

public Integer aadhar;
public Integer id;

private void writeObject(ObjectOutputStream out) throws IOException {
throw new NotSerializableException();
}

private Object readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new NotSerializableException();

}

}

3) Serialize Implementation Example 

public class SerializeEx {
public static void main(String[] args) {
Child e = new Child();
e.name = “Siva”;
e.address = “Bangalore”;
e.aadhar = 11122333;
e.id = 101;
try {
FileOutputStream fileOut = new FileOutputStream(“child.ser”);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf(“Serialized data is saved in child.ser”);
} catch (IOException i) {
i.printStackTrace();
}
}
}

4) Error:

Wile Running this program:

java.io.NotSerializableException

at com.ts.test.serli.Child.writeObject(Child.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.ts.test.serli.SerializeEx.main(SerializeEx.java:17)

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: