Today, when we look at the Struts1 source code, the Actionform first declares two protected variables of the transient type.
I have not contacted the transient type before, so I looked it up.
Transient is the Java language's keyword, variable modifier. Suppose you use it to declare an instance variable. When an object is stored, its value does not need to be maintained.
In Java, an object can be serialized only if it implements the Serilizable interface. This serialization pattern of Java provides developers with a lot of convenience, and we can do this without having to relate to the process of detailed serialization, just to implement the Serilizable interface for this class. All the properties and methods of this will be self-serialized.
However, in the actual development process, we often encounter this problem, some of the properties of this class need to be serialized, and other properties do not need to be serialized. Admittedly, you can allow this class to implement the Externalizable interface, which is a serilizable sub-interface, but you must implement the Readexternal and Writeexternal methods. You can implement the deserialization and serialization of detailed properties in both methods. This means, however, that you must manually write additional code in both methods to serialize the detailed properties.
This is where transient comes in handy, you just need to implement the Serilizable interface, you will not need to serialize the attributes before adding keywordtransient, serializing the object. This property is not serialized to the specified destination.
And in the struts source code. Actionform is indeed implement Serilizable interface.
Here is a sample sample. From the results of the implementation can be seen clearly
public class Testtransient {public static void main (string[] args) throws FileNotFoundException, IOException, Classnotfou ndexception { A A = new A (25, "name"); System.out.println (a); ObjectOutputStream oos = new ObjectOutputStream (New FileOutputStream ("C://transient.txt")); Oos.writeobject (a); Oos.close (); ObjectInputStream ois = new ObjectInputStream (New FileInputStream ("C://transient.txt")); A = (a) ois.readobject (); System.out.println (a); }}class a implements Serializable{int a;transient String b;public A (int a,string b) { this.a = A; this.b = b;} Public String toString () { return "a =" +a+ ", B =" +b;}}
The results of the execution are as follows:
A = 25,b = Name
A = 25,b = null
In the example above, I joined Keywordtransient in front of attribute B, and we saw that although we serialized the property value of object A as "Zhang San", we found that the property was empty after deserialization. Indicates that this property is not serialized.
Java Foundation--transient