"Java supplements" Java transient keyword

Source: Internet
Author: User

    • 1. The role of transient and how to use it
    • 2. Transient use summary
    • 3. Transient use details-are the variables modified by the transient keyword really not serialized?
1. The role of transient and how to use it

We all know that an object can be serialized as long as the Serilizable interface is implemented, and the Java serialization pattern provides developers with a lot of convenience, and we don't have to relate to the process of specific serialization, as long as this class implements the Serilizable interface, All properties and methods of this class are automatically serialized.

However, in the actual development process, we often encounter such problems, some properties of this class need to serialize, and other attributes do not need to be serialized , for example, if a user has some sensitive information (such as password, bank card number, etc.), for the sake of security, You do not want to be transferred in a network operation (primarily involving serialization operations, where the local serialization cache is also applicable), and the variables corresponding to these information can be added to the transient keyword. In other words, the life cycle of this field is only stored in the caller's memory and is not persisted to disk.

In short, the Java transient keyword is convenient for us, you only need to implement the Serilizable interface, will not need to serialize the attributes before adding the keyword transient, when serializing the object, This property is not serialized to the specified destination.

The example code is as follows:

Import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import java.io.Serializable; /** * @description Use the transient keyword to not serialize a variable * Note that when reading, the order of reading data must be consistent with the order in which the data is stored * * @author Alexia * @date 2013        -10-15 */public class Transienttest {public static void main (string[] args) {User user = new User ();        User.setusername ("Alexia");         USER.SETPASSWD ("123456");        System.out.println ("Read before Serializable:");        System.out.println ("Username:" + user.getusername ());         System.err.println ("Password:" + user.getpasswd ());            try {objectoutputstream os = new ObjectOutputStream (New FileOutputStream ("C:/user.txt")); Os.writeobject (user);            Writes the user object into the file Os.flush ();        Os.close (); } catch (FileNotFoundException e) {e.printstacktrAce ();        } catch (IOException e) {e.printstacktrace (); try {ObjectInputStream is = new ObjectInputStream (New FileInputStream ("C:/user.tx            T ")); user = (user) is.readobject ();             Reads the user's data Is.close () from the stream;            System.out.println ("\nread after Serializable:");            System.out.println ("Username:" + user.getusername ());         System.err.println ("Password:" + user.getpasswd ());        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();        } catch (ClassNotFoundException e) {e.printstacktrace ();       }}} class User implements Serializable {private static final long serialversionuid = 8294180014912103005L;    Private String username;     private transient String passwd;    Public String GetUserName () {return username;    } public void Setusername (String username) {    This.username = Username;    } public String getpasswd () {return passwd;    } public void setpasswd (String passwd) {this.passwd = passwd; } }

The output is:

read before Serializable: username: Alexiapassword: 123456 read after Serializable: username: Alexiapassword: null

The password field is null, stating that no information was obtained from the file at all when deserializing.

2. Transient use summary
    • 1) Once the variable is transient modified, the variable will no longer be part of the object persistence, and the variable content cannot be accessed after serialization.

    • 2) The Transient keyword can only modify variables, not methods and classes. Note that local variables cannot be modified by the transient keyword. If the variable is a user-defined class variable, the class needs to implement the serializable interface.

    • 3) Variables modified by the Transient keyword can no longer be serialized, and a static variable cannot be serialized, whether or not it is transient modified.

3rd may be some people are confused, because found in the user class in the Username field with the static keyword, the program operation results are still unchanged, that is, the static type of username also read out as "Alexia", this does not contradict with the 3rd said? This is actually true: 3rd is True (a static variable cannot be serialized regardless of whether it is transient), and the value of the static variable username in the deserialized class is the value of the corresponding static variable in the current JVM. This value is not deserialized in the JVM, do not believe? Well, here's what I'm going to prove:

Import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import java.io.Serializable; /** * @description Use the transient keyword to not serialize a variable * Note that when reading, the order of reading data must be consistent with the order in which the data is stored * * @author Alexia * @date 2013        -10-15 */public class Transienttest {public static void main (string[] args) {User user = new User ();        User.setusername ("Alexia");         USER.SETPASSWD ("123456");        System.out.println ("Read before Serializable:");        System.out.println ("Username:" + user.getusername ());         System.err.println ("Password:" + user.getpasswd ());            try {objectoutputstream os = new ObjectOutputStream (New FileOutputStream ("C:/user.txt")); Os.writeobject (user);            Writes the user object into the file Os.flush ();        Os.close (); } catch (FileNotFoundException e) {e.printstacktrAce ();        } catch (IOException e) {e.printstacktrace ();             } try {//Change the value of username before deserializing user.username = "Jmwang";            ObjectInputStream is = new ObjectInputStream (New FileInputStream ("C:/user.txt")); user = (user) is.readobject ();             Reads the user's data Is.close () from the stream;            System.out.println ("\nread after Serializable:");            System.out.println ("Username:" + user.getusername ());         System.err.println ("Password:" + user.getpasswd ());        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();        } catch (ClassNotFoundException e) {e.printstacktrace ();       }}} class User implements Serializable {private static final long serialversionuid = 8294180014912103005L;    public static String username;     private transient String passwd;  Public String GetUserName () {      return username;    } public void Setusername (String username) {this.username = username;    } public String getpasswd () {return passwd;    } public void setpasswd (String passwd) {this.passwd = passwd; } }

The result of the operation is:

read before Serializable: username: Alexiapassword: 123456 read after Serializable: username: jmwangpassword: null

static members cannot be serialized because static members are loaded with the load of the class, have a common survival with the class, and the default initial value of the static member is 0 , which means that the value of the static variable username in the deserialized class is the value of the corresponding static variable in the current JVM , which is modified after Jmwang, instead of the value Alexia when serialized. static Members are class-level, so they cannot be serialized, and serialization simply serializes an object, where "cannot serialize" means that the static member field is not included in the serialization information

3. Transient use details-are the variables modified by the transient keyword really not serialized?

Consider the following example:

Import Java.io.externalizable;import java.io.file;import java.io.fileinputstream;import java.io.FileOutputStream; Import Java.io.ioexception;import java.io.objectinput;import Java.io.objectinputstream;import java.io.ObjectOutput ; Import Java.io.ObjectOutputStream; /** * @descripiton The use of externalizable interface * * @author Alexia * @date 2013-10-15 * */public class Externalizabletest Implemen     TS externalizable {private transient String content = "Yes, I will be serialized, regardless of whether I am modified by the transient keyword";    @Override public void Writeexternal (ObjectOutput out) throws IOException {out.writeobject (content);        } @Override public void Readexternal (ObjectInput in) throws IOException, ClassNotFoundException {    Content = (String) in.readobject ();        } public static void Main (string[] args) throws Exception {externalizabletest et = new externalizabletest ();        ObjectOutput out = new ObjectOutputStream (new FileOutputStream (New File ("Test")); Out.wrIteobject (ET);        ObjectInput in = new ObjectInputStream (New FileInputStream ("Test"));        ET = (externalizabletest) in.readobject ();         System.out.println (et.content);        Out.close ();    In.close (); }}

Will the content variables be serialized? Well, I lost the answer, yes, the result is:

是的,我将会被序列化,不管我是否被transient关键字修饰

What is this, not to say that the variables of the class will not be serialized after the Transient keyword is modified?

We know that in Java, the serialization of objects can be achieved by implementing two interfaces, if the implementation of the serializable interface, then all the serialization will be automatic, if the implementation of the Externalizable interface, then nothing can be automatically serialized, You need to manually specify the variable you want to serialize in the Writeexternal method, regardless of whether it is transient decorated. So the second example outputs the contents of the variable content initialization, NOT NULL.

"Java supplements" Java transient keyword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.