Java Reference
In-Depth Information
The MyClass uses 801890 as the value for serialVersionUID . This number was chosen arbitrarily. It does not
matter what number you choose for this field. The JDK ships with a serialver tool that you can use to generate the
value for the serialVersionUID field of your class. You can use this tool at the command prompt as follows:
serialver -classpath <your-class-path> <your-class-name>
When you run this tool with your class name, it prints the declaration of the serialVersionUID field for your class
with the generated SUID for it. You just need to copy and paste that declaration into your class declaration.
Suppose you have a class that does not contain a serialVersionUID field and you have serialized its object. If
you change your class and try to deserialize the object, the Java runtime will print an error message with the expected
serialVersionUID . You need to add the serialVersionUID field in your class with the same value and try deserializing
the objects.
Tip
Stopping Serialization
How do you stop the serialization of objects of your class? Not implementing the Serializable interface in your class
seems to be an obvious answer. However, it is not a valid answer in all situations. For example, if you inherit your class
from an existing class that implements the Serializable interface, your class implements the Serializable interface
implicitly. This makes your class automatically serializable. To stop objects of your class from being serialized all the
time, you can add writeObject() and readObject() methods in your class. These methods should simply throw an
exception. Note that in Listing 7-31 you are implementing the Serializable interface and still it is not serializable
because you are throwing an exception in the readObject() and writeObject() methods.
Listing 7-31. Stopping a Class from Serializing
// NotSerializable.java
package com.jdojo.io;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class NotSerializable implements Serializable {
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
// Throw an exception
throw new IOException("Not meant for serialization!!!");
}
private void writeObject(ObjectOutputStream os) throws IOException {
// Throw an exception
throw new IOException("Not meant for serialization!!!");
}
// Other code for the class goes here
}
 
 
Search WWH ::




Custom Search