This article brings to you the content is about Java transient keyword Usage analysis (code), there is a certain reference value, the need for friends can refer to, I hope to help you.
1, the role of transient and the use of the method
As long as an object implements the Serilizable interface, this object can be serialized, so long as the class implements the Serilizable interface, all the properties and methods of the 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 two:
(1) If a user has some sensitive information (such as password, bank card number, etc.), in order to be safe, do not want to be transferred in the network operation (mainly involves the serialization operation, the local serialization cache also applies), this information corresponding variable can add 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.
(2) The value of the field in the class can be deduced from other fields, such as a rectangle class has three properties: length, width, area (example, generally do not design), then at the time of serialization, the area of this property is not necessary to be serialized;
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 * */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; } }
Output to
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 result
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) A static variable cannot be serialized, whether or not it is transient modified.
3) Transient keyword decoration scope, can only modify the variables, but not the 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.
2nd 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 * */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: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 the details--The Transient keyword modified by the variables can really not be serialized?
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 * */public class Externalizabletest implements externalizable {private Transie NT 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:
1 |
是的,我将会被序列化,不管我是否被 transient 关键字修饰
|
What is this, not to say that the variables of the class will not be serialized after the Transient keyword is modified?
In Java, the serialization of an object can be achieved by implementing two interfaces:
(1) If the serializable interface is implemented, all serialization will be automatically
(2) If the Externalizable interface is implemented, nothing can be automatically serialized, and it is necessary to manually specify the variable to be serialized 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.