How to use transient in Java
Transient in the Java language is not as well-known as class, synchronized and other familiar keywords, so it will appear in some interview questions. In this article I will explain transient to you.
Use of transient
Q: What can the transient keyword achieve?
A: When the object is serialized (writes the byte sequence to the target file), transient prevents the variables declared with this keyword in the instance from being persisted; when the object is deserialized (from The source file reads the byte sequence for reconstruction), such instance variable values will not be persisted and restored. For example, when deserializing an object - a data stream (for example, a file) may not exist, the reason is that there are variables of type java.io.InputStream in your object, and the input streams referenced by these variables cannot be opened during serialization. .
Introduction to using transient
Q: How to use transient?
A: Contains the transient modifier in the instance variable declaration. Snippet 1 provides a small demonstration.
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io .IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class ClassLib implements Serializable { private transient InputStream is; private int majorVer; private int minorVer; ClassLib(InputStream is) throws IOException { System.out.println("ClassLib(InputStream) called"); this.is = is; DataInputStream dis; if (is instanceof DataInputStream) dis = (DataInputStream) is; else dis = new DataInputStream(is); if (dis.readInt() != 0xcafebabe) throw new IOException("not a .class file"); minorVer = dis.readShort(); majorVer = dis.readShort(); } int getMajorVer() { return majorVer; } int getMinorVer() { return minorVer; } void showIS() { System.out.println(is); } } public class TransDemo { public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("usage: java TransDemo classfile"); return; } ClassLib cl = new ClassLib(new FileInputStream(args[0])); System.out.printf("Minor version number: %d%n", cl.getMinorVer()); System.out.printf("Major version number: %d%n", cl.getMajorVer()); cl.showIS(); try (FileOutputStream fos = new FileOutputStream("x.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(cl); } cl = null; try (FileInputStream fis = new FileInputStream("x.ser"); ObjectInputStream ois = new ObjectInputStream(fis)) { System.out.println(); cl = (ClassLib) ois.readObject(); System.out.printf("Minor version number: %d%n", cl.getMinorVer()); System.out.printf("Major version number: %d%n", cl.getMajorVer()); cl.showIS(); } catch (ClassNotFoundException cnfe) { System.err.println(cnfe.getMessage()); } } }
Fragment 1: Serializing and Deserializing ClassLib Objects
The ClassLib and TransDemo classes are declared in Fragment 1. ClassLib is a library that reads Java class files and implements the java.io.Serializable interface so that these instances can be serialized and deserialized. TransDemo is an application class used to serialize and deserialize ClassLib instances.
ClassLib declares its instance variables as transient because it can meaninglessly serialize an input stream (as described above). In fact, if this variable is not transient, java.io.NotSerializableException will be thrown when deserializing the contents of x.ser because the InputStream does not implement the Serializable interface.
Compile fragment 1: javac TransDemo.java; run the application with one parameter TransDemo.class: java TransDemo TransDemo.class. You may see output similar to the following:
ClassLib(InputStream) called Minor version number: 0 Major version number: 51 java.io.FileInputStream@79f1e0e0 Minor version number: 0 Major version number: 51 null
The above output shows that when the object is reconstructed, no constructor method is called. Additionally, is is assumed to default to null, in contrast to majorVer and minorVer which have values when the ClassLib object is serialized.
Member variables and transient in a class
Q: Can transient be used in member variables in a class?
A: For the answer to the question, please see Fragment 2
public class TransDemo { public static void main(String[] args) throws IOException { Foo foo = new Foo(); System.out.printf("w: %d%n", Foo.w); System.out.printf("x: %d%n", Foo.x); System.out.printf("y: %d%n", foo.y); System.out.printf("z: %d%n", foo.z); try (FileOutputStream fos = new FileOutputStream("x.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(foo); } foo = null; try (FileInputStream fis = new FileInputStream("x.ser"); ObjectInputStream ois = new ObjectInputStream(fis)) { System.out.println(); foo = (Foo) ois.readObject(); System.out.printf("w: %d%n", Foo.w); System.out.printf("x: %d%n", Foo.x); System.out.printf("y: %d%n", foo.y); System.out.printf("z: %d%n", foo.z); } catch (ClassNotFoundException cnfe) { System.err.println(cnfe.getMessage()); } } }
Fragment 2: Serializing and Deserializing Foo Objects
Fragment 2 is somewhat similar to Fragment 1. But the difference is that it is the Foo object that is serialized and deserialized, not ClassLib. Furthermore, Foo contains a pair of variables, w and x, and instance variables y and z.
Compile fragment 2 (javac TransDemo.java) and run the application (java TransDemo). You can see the following output:
w: 1 x: 2 y: 3 z: 4 w: 1 x: 2 y: 3 z: 0
This output tells us that the instance variable y is serialized, but z is not. It is marked transient. However, when Foo is serialized, it does not tell us whether the variables w and x are serialized and deserialized, or whether they are just initialized in the normal class initialization manner. For the answer, we need to look at the contents of x.ser.
The x.ser hex is shown below:
00000000 AC ED 00 05 73 72 00 03 46 6F 6F FC 7A 5D 82 1D ....sr..Foo.z].. 00000010 D2 9D 3F 02 00 01 49 00 01 79 78 70 00 00 00 03 ..?...I..yxp....
Thanks to the article "The Java serialization algorithm revealed" in JavaWorld, we found out the meaning of the output:
AC ED serialization protocol identification
00 05 stream version number
73 means this is a new object
72 means this is a new class
00 03 Represents the class name length (3)
46 6F 6F Represents the class name (Foo)
FC 7A 5D 82 1D D2 9D 3F Represents the serial version of the class Identifier
02 indicates that the object supports serialization
00 01 indicates the number of variables of this class (1)
49 Variable type code (0×49, or I, Represents int)
00 01 Represents the variable name length (1)
79 Variable name (y)
78 Represents the end of the optional data block of the object
70 indicates that we have reached the top of the class hierarchy
00 00 00 03 indicates the value of y (3)
Obviously, only the instance variable y is serialized. Because z is transient, it cannot be serialized. Furthermore, even if they are marked transient, w and x cannot be serialized, because their class variables cannot be serialized.
The above is the content of how to use transient in Java. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
