import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.Serializable; class Employee implements Serializable{ private String name; private int age; public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } public String getName(){ return name; } public int getAge(){ return age; } } public class Main{ public static void main(String[] args) throws Exception{ FileInputStream file = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(file); Employee emp = new Employee(); emp.readFields(in.defaultReadObject()); System.out.println("Name: " + emp.getName()); System.out.println("Age: " + emp.getAge()); in.close(); file.close(); } }
import java.io.*; class Person implements Serializable{ private String name; private int age; private transient String address; public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } public void setAddress(String address){ this.address = address; } public String getName(){ return name; } public int getAge(){ return age; } public String getAddress(){ return address; } } public class Main{ public static void main(String[] args) throws Exception{ FileInputStream file = new FileInputStream("person.ser"); ObjectInputStream in = new ObjectInputStream(file); Person person = new Person(); person.readFields(in.defaultReadObject()); System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); System.out.println("Address: " + person.getAddress()); in.close(); file.close(); } }In this example, we are reading an object of type Person from a serialized file. The Person class has a transient field named address, which means it is not serialized. When we call readFields() method, it will not initialize the address field. Finally, we print the name, age, and address of the person. This method is part of the java.io package library.