Java - ObjectInputStream.GetField Class



Introduction

The Java ObjectInputStream.GetField class provide access to the persistent fields read from the input stream.

Class declaration

Following is the declaration for Java.io.ObjectInputStream.GetField class −

public abstract static class ObjectInputStream.GetField
   extends Object

Class constructors

Sr.No. Constructor & Description
1

ObjectInputStream.GetField()

Single Constructor

Class methods

Sr.No. Method & Description
1 abstract boolean defaulted(String name)

This method return true if the named field is defaulted and has no value in this stream.

2 abstract boolean get(String name, boolean val)

This method gets the value of the named boolean field from the persistent field.

3 abstract byte get(String name, byte val)

This method gets the value of the named byte field from the persistent field.

4 abstract char get(String name, char val)

This method gets the value of the named char field from the persistent field.

5 abstract double get(String name, double val)

This method gets the value of the named double field from the persistent field.

6 abstract float get(String name, float val)

This method gets the value of the named float field from the persistent field.

7 abstract int get(String name, int val)

This method gets the value of the named int field from the persistent field.

8 abstract long get(String name, long val)

This method gets the value of the named long field from the persistent field.

9 abstract Object get(String name, Object val)

This method get the value of the named Object field from the persistent field.

10 abstract short get(String name, short val)

This method gets the value of the named short field from the persistent field.

11 abstract ObjectStreamClass getObjectStreamClass()

This method gets the ObjectStreamClass that describes the fields in the stream.

Methods inherited

This class inherits methods from the following classes −

  • Java.io.Object

Example - Checking for a Missing Field

The following example shows the usage of ObjectInputStream.getField defaulted() method. This example serializes an object and then deserialize the object and check if the field was defaulted.

ObjectInputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      String filename = "person_data1.bin";

      // Step 1: Serialize the object
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         Person person = new Person("Alice", 0);
         oos.writeObject(person);
         System.out.println("Person object serialized.");
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Step 2: Deserialize and check if `age` was defaulted
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         Person deserializedPerson = (Person) ois.readObject(); 
      } catch (IOException | ClassNotFoundException e) {
         e.printStackTrace();
      }
   }

   static class Person implements Serializable {
      private static final long serialVersionUID = 1L;

      String name;
      int age; // `transient` field is NOT serialized

      public Person(String name, int age) {
         this.name = name;
         this.age = age;
      }

      // Custom deserialization method
      private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         System.out.println("Inside readObject method *****");
         ObjectInputStream.GetField fields = ois.readFields(); // Get serialized fields

         String name = (String)fields.get("name", "Unknown"); // Read `name`
         int age = fields.get("age", 0);

         // Check if `age` was serialized or missing
         if (fields.defaulted("name")) {
            System.out.println("Field 'name' was defaulted (not found in stream).");
            age = 0; // Assign default value
         } else {
            System.out.println("Field 'name' was not defaulted");
         }
      }

      @Override
      public String toString() {
         return "Person{name='" + name + "', age=" + age + "}";
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Person object serialized.
Inside readObject method *****
Field 'name' was not defaulted

Explanation

  • During deserialization, defaulted("name") returns false because the name field was found in the stream.

Example - Read a Serialized byte Field Normally

The following example shows the usage of ObjectInputStream.getField get(String name, byte val) method. This example shows how to read a byte field that was serialized.

ObjectInputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectInputStreamDemo {
   public static void main(String[] args) throws Exception {
      String filename = "byte1.ser";

      // Serialize
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         Data data = new Data((byte) 42);
         oos.writeObject(data);
      }

      // Deserialize
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         Data d = (Data) ois.readObject();
      }
   }

   static class Data implements Serializable {
      private static final long serialVersionUID = 1L;
      byte number;

      Data(byte number) {
         this.number = number;
      }

      private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField fields = ois.readFields();
         byte num = fields.get("number", (byte) 0);
         System.out.println("Deserialized number: " + num);
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Deserialized number: 42

Explanation

  • The get("number", (byte) 0) retrieves the stored value 42.

  • The second argument ((byte) 0) is only used if the field is missing.

Example - Usage of ObjectInputStream.getField get(String name, byte val) method

The following example shows the usage of ObjectInputStream.getField get(String name, byte val) method.

ObjectInputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;

public class ObjectInputStreamDemo implements Serializable {
   public static void main(String[] args) {
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeObject(new Example());
         oout.flush();
         oout.close();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read an object from the stream and cast it to Example
         Example a = (Example) ois.readObject();

         // print var variable of a
         System.out.println("" + a.var);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }

   static public class Example implements Serializable {
      static byte var = 5;
      
      // assign a new serialPersistentFields 
      private static final ObjectStreamField[] serialPersistentFields = {
         new ObjectStreamField("var", Byte.TYPE)
      };

      private void readObject(ObjectInputStream in)
         throws IOException, ClassNotFoundException {

         // get the field and assign it at string variable
         ObjectInputStream.GetField fields = in.readFields();

         // check if string is defaulted, meaning if it has no value
         byte b = 0;
         var = (byte) fields.get("var", b);
      }

      private void writeObject(ObjectOutputStream out) throws IOException {

         // write into the ObjectStreamField array the variable var
         ObjectOutputStream.PutField fields = out.putFields();
         fields.put("var", var);
         out.writeFields();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

5
Advertisements