Example code on how to prevent serialization:
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;
//Serializable class
class Animal implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
//Does not want to be serializable
class Cat extends Animal {
private static final long serialVersionUID = 1L;
private String breed;
private static final String NOT_SERIALIZABLE = "Cat cannot be serialized";
public Cat (String name, String breed) {
super(name);
this.breed = breed;
}
public String getBreed() {
return breed;
}
//To prevent serialization, override this method to throw exception
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
throw new NotSerializableException(NOT_SERIALIZABLE);
}
//To prevent serialization, override this method to throw exception
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException(NOT_SERIALIZABLE);
}
}
//Test it
public class MyNonSerializableTest {
public static void main(String[] args) throws FileNotFoundException, IOException {
Animal a = new Animal("Cow");
System.out.println("Serializing animal object");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("animal.ser"));
out.writeObject(a);
Cat c = new Cat("bo", "Taby cat");
System.out.println("Serializing cat object");
ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream("cat.ser"));
ous.writeObject(c);
}
}
The output:
Serializing animal object
Serializing cat object
Exception in thread "main" java.io.NotSerializableException: Cat cannot be serialized
....blah blah blah.....
No comments:
Post a Comment