Java transient keywords use small notes

Source: Internet
Author: User
Tags serialization

Hey, although the most familiar is Java, but a lot of Java basic knowledge is not known, such as transient keyword has not been used before, so do not know what its role is, today to do a pen test found a question is about this, so spend a time to organize the use of transient key words, Up and down Posture ~ ~ ~ Well, nonsense not much to say, below the beginning:

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 a problem, 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 security purposes, do not want to operate in the network (mainly involved in serialization operations, Local serialization cache is also applicable), the variable that corresponds to this 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 property before adding the keyword transient, when serializing the object, this property will not be 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; }}
View Code

The output is:

Read before Serializable:username:alexiapassword:123456read 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; }}
View Code

The result of the operation is:

Read before Serializable:username:alexiapassword:123456read after Serializable:username:jmwangpassword:null

This indicates that the value of the static variable username in the class after deserialization is the value of the corresponding static variable in the current JVM, which is Alexia after the modified Jmwang instead of the value at the time of serialization.

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 externalizable interface * * @author Alexia * @date 2013-10-15 * */publi C Class Externalizabletest implements Externalizable {private transient String content = "Yes, I will be serialized, regardless of whether I am transient key    Word decoration ";    @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 Externalizablete        St ();        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:

Yes, I will be serialized, no matter if I am modified by the transient keyword

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 transient keywords use small notes

Related Article

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.