Java serialization provides a mechanism for persistence object instances. When a persistent object is stored, there may be a special object data member. We do not want to use the serialization mechanism to save it. To disable serialization on a domain of a specific object, you can add the keyword transient before this domain.
Transient is a keyword of the Java language used to indicate that a domain is not part of the object's serialization. When an object is serialized, the value of the transient variable is not included in the serialized representation. However, non-transient variables are included.
First, let's look at some java serialization code:
Public class logginginfo implements java. Io. serializable
{
Private date loggingdate = new date ();
Private string uid;
Private transient string PWD;
Logginginfo (string user, string password)
{
Uid = user;
Pwd = password;
}
Public String tostring ()
{
String Password = NULL;
If (Pwd = NULL)
{
Password = "not set ";
}
Else
{
Password = PWD;
}
Return "Logon info: \ n" + "User:" + uid +
"\ N logging Date:" + loggingdate. tostring () +
"\ N password:" + password;
}
}
Now we create an instance of this class, serialize it, and write this serialized object to the disk.
Logginginfo loginfo = new logginginfo ("Mike", "mechanic ");
System. Out. println (loginfo. tostring ());
Try
{
Objectoutputstream o = new objectoutputstream (New fileoutputstream ("loginfo. Out "));
O. writeobject (loginfo );
O. Close ();
}
Catch (exception e) {// deal with exception}
To read the object back, we can write
Try
{
Objectinputstream in = new objectinputstream (New fileinputstream ("loginfo. Out "));
Logginginfo loginfo = (logginginfo) in. readobject ();
System. Out. println (loginfo. tostring ());
}
Catch (exception e) {// deal with exception}
If we run this code, we will notice that the print password of the object read back (read -- back (de-serializing) from the disk is "not set ". This is the expected result when we define the PWD domain as transient.
Now, let's take a look at the potential problems caused by careless handling of the transient domain. Suppose we modified the class definition and provided a default value for the transient domain,
The Code is as follows:
Public class guestlogginginfo implements java. Io. serializable
{
Private date loggingdate = new date ();
Private string uid;
Private transient string PWD;
Guestlogginginfo ()
{
Uid = "guest ";
Pwd = "guest ";
}
Public String tostring ()
{
// Same as abve
}
}
Now, if we serialize an instance of guestlogginginfo, write it to the disk, and read it from the disk, we still see that the printed password of the read object is "not set ". When an instance of a class is read from a disk, the constructor of the class is not executed, but the persistence state of the Class Object is loaded, and assign this status to another object of this class.
From: http://www.devx.com/tips/Tip/13726