Java – What is transient fields?

In Java, transient fields are excluded in the serialization process. In short, when we save an object into a file (serialization), all transient fields are ignored.

1. POJO + transient

Review the following Person class; the salary field is transient.


public class Person implements Serializable {

    private static final long serialVersionUID = 1L;

    private String name;
    private int age;

    // ignore this field
    private transient BigDecimal salary;

    //...
}

2. Serialization

2.1 During the serialization, the transient field salary will exclude.

ObjectUtils.java

package com.mkyong.io.object;

import java.io.*;
import java.math.BigDecimal;

public class ObjectUtils {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        Person person = new Person("mkyong", 40, new BigDecimal(900));

        // object -> file
        try (FileOutputStream fos = new FileOutputStream("person.obj");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(person);
            oos.flush();
        }

        Person result = null;
        // file -> object
        try (FileInputStream fis = new FileInputStream("person.obj");
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            result = (Person) ois.readObject();
        }

        System.out.println(result);

    }

}

Output

Terminal

Person{name='mkyong', age=40, salary=null}

2.2 Now, we removed the transient keyword.

Person.java

public class Person implements Serializable {

    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private BigDecimal salary;

    //...
}

Rerun it, this time, the salary field will be displayed.

Terminal

Person{name='mkyong', age=40, salary=900}  

Done.

Download Source Code

$ git clone https://github.com/mkyong/core-java.git

$ cd java-io

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar