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.favtuts.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("favtuts", 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

Person{name='favtuts', 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.

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

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/object

References

Leave a Reply

Your email address will not be published. Required fields are marked *