About Lesson
The transient
keyword in Java is used to indicate that a field should not be serialized. When an object is serialized, the fields marked as transient
are ignored and are not included in the serialized representation of the object. This can be useful for fields that contain sensitive information or data that is transient by nature, such as temporary data that should not be persisted.
To delcare a field transient, place the keyword transient
before the field declaration. During serialization, transient fields are skipped. Upon deserialization, they are initialized to their default values.
Syntax
class ExampleClass implements Serializable {
private static final long serialVersionUID = 12345L;
private String name;
private transient int age;
}
Code Example
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private transient int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializePerson {
public static void main(String[] args) {
Person person = new Person("John", 30);
try (FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(person);
System.out.println("Serialized data is saved in person.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeserializePerson {
public static void main(String[] args) {
Person person = null;
try (FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
person = (Person) in.readObject();
System.out.println("Deserialized Person: " + person);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}