Understanding Java's transient Keyword: Definition, Conventions, Usage Scenarios, and Serialization Behavior
This article explains the transient keyword in Java, covering its definition, the rules that govern its use, practical examples with Gson serialization, the impact on object fields during serialization, and how Externalizable can override its behavior, providing a comprehensive guide for developers.
Preface
While reading the source code of HashMap , I noticed that the internal table array is declared with the transient keyword. Curious about this rarely used modifier, I decided to summarize the basic knowledge of transient and share it with fellow developers.
Definition of the transient keyword
The transient keyword is closely related to object serialization . When an object is transmitted over a network or stored to a file, it is first serialized into a byte stream and later deserialized back into an object instance.
What is serialization/deserialization?
In Java, serialization converts an object into a sequence of bytes that contain the object's data and type information. The resulting byte stream can be written to a database, a file, or sent over the network. Deserialization restores the original object from this byte sequence.
Conventions of the transient keyword
Convention 1: transient can only modify variables, not methods or classes. Local variables cannot be marked transient .
Convention 2: Fields marked with transient are excluded from serialization; after deserialization they will be null or default values.
Convention 3: Static fields are never serialized, regardless of whether they are also marked transient .
Usage scenarios
Consider a simple Product class with three fields: amounts , price , and sum . The sum field can be derived from price * amounts , so it does not need to be serialized.
public class Product{
private int amounts;
private int price;
private int sum;
}When the object is serialized with Gson, the resulting JSON contains only amounts and price because sum is not marked transient yet.
{"amounts":3,"price":2,"sum":6}After adding the transient modifier to sum :
public class Product{
private int amounts;
private int price;
private transient int sum;
}and serializing:
public static void main(String[] args){
Product p = new Product();
p.setAmounts(3);
p.setPrice(2);
p.setSum(p.getAmounts()*p.getPrice());
String json = new Gson().toJson(p);
System.out.println(json);
}The console prints:
{"amounts":3,"price":2}This demonstrates that a field marked transient is omitted by Gson during serialization.
Object property inference
If a property value can be derived from other properties or methods, it should not be serialized.
Gson’s internal ReflectiveTypeAdapterFactory examines each field via excludeField() . The method checks the field’s modifiers with a bitwise & operation against Modifier.TRANSIENT (and Modifier.STATIC ) to decide whether to skip the field.
public boolean excludeField(Field field, boolean serialize){
// modifiers = Modifier.TRANSIENT | Modifier.STATIC;
if ((modifiers & field.getModifiers()) != 0){
return true; // skip serialization
}
}Static fields are also excluded, as indicated by Convention 3.
Can a transient field ever be serialized?
Java provides two serialization mechanisms: implementing Serializable or Externalizable . The latter requires explicit implementation of writeExternal and readExternal , allowing developers to decide which fields to write, even if they are marked transient .
When a class implements Externalizable , the transient modifier no longer prevents a field from being written if the developer chooses to include it.
Summary of the transient keyword
Using Gson, a transient field is automatically excluded from JSON output.
When a class implements Externalizable , developers can manually serialize any field, regardless of the transient modifier.
Static fields are never serialized, whether or not they are also marked transient .
Standard Java I/O streams ( ObjectInputStream / ObjectOutputStream ) follow the same rules unless custom handling is provided.
References
https://www.cnblogs.com/chenpt/p/9415249.html
https://blog.csdn.net/u012723673/article/details/80699029
https://baijiahao.baidu.com/s?id=1636557218432721275&wfr=spider&for=pc
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.