Java transient keyword using the small note _java

Source: Internet
Author: User
Tags flush serialization

Hey, although the most familiar is the Java, but a lot of Java basics do not know, such as the transient keyword has not been used before, so do not know what its role is, today to do a pen test to find a problem is about this, so spend a time to tidy up the use of transient keyword, Up the Posture ~ ~ ~ Well, no more nonsense to say, the following start:
1. The function of transient and its use method
We all know that an object can be serialized as long as it implements the Serilizable interface, and this serialization pattern of Java provides a lot of convenience for developers, and we can do without the process of specific serialization, as long as the class implements the Serilizable interface, All of the properties and methods of this class are automatically serialized.
However, in the actual development process, we often encounter such a problem, some attributes of this class need to be serialized, and other attributes need not be serialized, for example, if a user has some sensitive information (such as passwords, bank card numbers, etc.), for security reasons, do not want to operate in the network (mainly involving serialization operations, The local serialization cache is also applicable), and the corresponding variable can be added to the transient keyword. In other words, the lifecycle of this field is only stored in the caller's memory and not written to the disk for persistence.
In short, the Java transient keyword for us to facilitate, you only need to implement the Serilizable interface, will not need to serialize the attribute before adding a keyword transient, serialization of objects, this property will not be serialized to the specified destination.

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 to read the data must be consistent with the order in which the data is stored * * @author Alexia * @date 2013-10-
    */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 a file Os.flush ();
    Os.close ();
    catch (FileNotFoundException e) {e.printstacktrace ();
  catch (IOException e) {    E.printstacktrace ();
      The try {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;
  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:alexia
password:123456

read after Serializable: 
Username:alexia
Password:null 

The password field is null, which indicates that no information was obtained from the file at the time of deserialization.

2. Summary of the use of transient
1 Once a variable is transient decorated, the variable will no longer be part of the object's persistence, and the contents of the variable cannot be accessed after serialization.
2 The Transient keyword can only modify variables, not methods and classes. Note that local variables cannot be decorated by the transient keyword. If the variable is a user-defined class variable, the class needs to implement the serializable interface.
3 The variables modified by the Transient keyword can no longer be serialized, and a static variable, whether or not modified by transient, cannot be serialized.
3rd, some people may be very confused, because found in the user class after the Username field with the static keyword, the program running the result is still unchanged, that is, the static type of username also read out as "Alexia", this is not the contradiction with the 3rd said? In fact, the 3rd is true (a static variable, whether or not it is transient modified, cannot be serialized), and the value of the static variable username in the class after deserialization 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 to read the data must be consistent with the order in which the data is stored * * @author Alexia * @date 2013-10-
    */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 a file Os.flush ();
    Os.close ();
    catch (FileNotFoundException e) {e.printstacktrace ();
  catch (IOException e) {    E.printstacktrace ();
      
      try {//change the value of the 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 results of the operation are:

Read before Serializable: 
username:alexia
password:123456

read after Serializable: 
Username:jmwang
Password:null 

This shows 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, Jmwang for modification, rather than the value Alexia when serialized.

3. Transient use details--Can the variables modified by the transient keyword really not be 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; Use of/** * @descripiton externalizable interface * * @author alexia * @date 2013-10-15 * */public class externalizabletest I

  Mplements 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 ("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 variable be serialized? Well, I lost the answer, yes, the result is:
Yes, I will be serialized, regardless of whether I am modified by the transient keyword
What is this, not to say that a variable of a class will not be serialized after it is modified by the transient keyword?
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 modified. So the second example outputs the contents of the variable content initialization, NOT NULL.

Author: Alexia (minmin)
If you would like to interact with me, welcome to the micro-bo mutual powder
Original connection: http://www.cnblogs.com/lanxuezaipiao/p/3369962.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.