Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the transient keyword in Java

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to use the transient keyword in Java. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

1. The function and usage of transient

We all know that as long as an object implements the Serilizable interface, the object can be serialized. This serialization mode of java provides a lot of convenience for developers. We do not have to care about the specific serialization process. As long as the class implements the Serilizable interface, all the properties and methods of the class will be serialized automatically.

However, in the actual development process, we often encounter the problem that some properties of this class need to be serialized, while others do not need to be serialized. For example, if a user has some sensitive information (such as password, bank card number, etc.), for security reasons, we do not want to be transmitted in network operations (mainly related to serialization operations, local serialization cache is also applicable). The variables corresponding to this information can be added with the transient keyword. In other words, the life cycle of this field is only stored in the caller's memory and not written to disk for persistence.

In short, java's transient keyword provides convenience for us. You only need to implement the Serilizable interface and add the keyword transient to the property that does not need to be serialized. 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 uses the transient keyword not to serialize a variable

* Note that when reading, the order in which the data is read 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); / / write the User object to a file

Os.flush ()

Os.close ()

} catch (FileNotFoundException e) {

E.printStackTrace ()

} catch (IOException e) {

E.printStackTrace ()

}

Try {

ObjectInputStream is = new ObjectInputStream (new FileInputStream (

"C:/user.txt"))

User = (User) is.readObject (); / / read User data from the stream

Is.close ()

System.out.println ("read 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, indicating that no information was obtained from the file during deserialization.

2. Summary of transient usage

1) once the variable is modified by transient, the variable is no longer part of object 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 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 it is modified by transient or not.

The third point may be very confusing for some people, because they find that after adding the static keyword to the username field in the User class, the running result of the program remains the same, that is, the username of static type is also read as "Alexia". Does this not contradict the third point? In fact, it goes like this: the third point is true (a static variable cannot be serialized whether it is modified by transient or not). 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 derived from JVM, not deserialization, do not believe? All right, let me prove it:

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 uses the transient keyword not to serialize a variable

* Note that when reading, the order in which the data is read 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); / / write the User object to a file

Os.flush ()

Os.close ()

} catch (FileNotFoundException e) {

E.printStackTrace ()

} catch (IOException e) {

E.printStackTrace ()

}

Try {

/ / change the value of username before deserialization

User.username = "jmwang"

ObjectInputStream is = new ObjectInputStream (new FileInputStream (

"C:/user.txt"))

User = (User) is.readObject (); / / read User data from the stream

Is.close ()

System.out.println ("read 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 running result is:

Read before Serializable:

Username: Alexia

Password: 123456

Read after Serializable:

Username: jmwang

Password: null

This 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 the modified jmwang, not the value Alexia when serialized.

3. Transient usage details-is it true that variables modified by the transient keyword cannot 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 implements Externalizable {

Private transient String content = "Yes, I will be serialized, whether or not 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 (new File (

"test")

Et = (ExternalizableTest) in.readObject ()

System.out.println (et.content)

Out.close ()

In.close ()

}

}

Will content variables be serialized? Well, I typed out all the answers, and yes, the result is:

Yes, I will be serialized, whether or not I am modified by the transient keyword

Why, doesn't it mean that the variables of the class will not be serialized after they are modified by the transient keyword?

We know that in Java, object serialization can be achieved by implementing two interfaces. If you implement the Serializable interface, all serialization will be carried out automatically. If you implement the Externalizable interface, nothing can be serialized automatically. You need to manually specify the serialized variable in the writeExternal method, regardless of whether it is modified by transient. So the second example outputs the initialization of the variable content, not null.

The above is how to use the transient keyword in Java. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report