When you are writing client-server software with Java, it's often convenient to pass Java objects from the client to the server. Java Serialization allows classes to be converted to a string format, allowing for easy network transmission. In most cases, it is very easy to make a class Serializable. You simply have your class implement the java.io.Serializable interface. Unlike most interfaces, there are no methods for you to implement, it is simply a "marking interface".
public class Person
implements Serializable
{
private Date mBirthday
private String mName
public Person (String pName, Date pBirthday)
{
mBirthday = new Date (pBirthday);
mName = pName;
}
/* add some setters / getters etc... */
}
Once you have a Serializable class, you can then create an ObjectOutputStream and use the writeObject method to send your object. If you try to write an object that is not Serializable, you will get a NotSerializableException.
There are some classes that just can not be serialized. Often these are AWT components, or Threads, or the like. But what if you have a class that you want to "make Serializable" but once of it's member variables is a Thread object. This is where the transient keyword comes in. By marking a member variable transient. You tell the Serialization engine not to include that member in the serialization process. You are now able to send down that complex object without getting a NotSerializableException. For example:
...
private Date mBirthday
private String mName
private transient Thread personThread
...
When a Person object gets deserialized, the personThread Thread will be null, but most likely, you won't care, especially in the case, where you just want to store the birthday and the name of the person.
For further reading, check out the discussion on Serialziation at the Sun Developer Network
-Alex
thanks! very useful information!
Posted by: max | October 09, 2007 at 10:56 AM