exclude fields from being serialized
If you want to exclude certain fields from being serialized and deserialized, you can mark them as `transient`. The `transient` keyword in Java is used to indicate that a field should not be serialized when the object is converted into a byte stream. This allows you to exclude sensitive information or fields that can be reconstructed from being included in the serialized form.

Table of Contents
Example
Let’s modify the `Employee` class to exclude the `id` field from serialization:
```java
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private transient int id; // Mark id field as transient
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
```
In this example, the `id` field is marked as `transient`. When an `Employee` object is serialized, the `id` field will not be included in the serialized form. When the object is deserialized, the `id` field will be initialized to its default value (`0` for `int`).
Serialization with Transient Fields
Here’s how you can serialize and deserialize an `Employee` object with a transient field:
```java
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Employee emp = new Employee("John Doe", 12345);
try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(emp);
System.out.println("Serialized data is saved in employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
public class DeserializeDemo {
public static void main(String[] args) {
Employee emp = null;
try (FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
emp = (Employee) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + emp.getName());
System.out.println("ID: " + emp.getId()); // Will print 0 because id is transient
}
}
```
Key Points
- Transient Fields: Fields marked as `transient` are excluded from the serialization process.
- Default Values: Transient fields are initialized to their default values (`0` for `int`, `null` for objects) when the object is deserialized.
- Selective Serialization: Use `transient` to exclude fields that do not need to be serialized, such as fields that can be recalculated or are not relevant to persistence.