Java - ObjectInputStream.GetField get(String name, int val) method



Description

The Java ObjectInputStream.getField get(String name, int val) method gets the value of the named int field from the persistent field, and if it wasn't serialized, it returns the default value you provide.

Declaration

Following is the declaration for java.io.ObjectInputStream.getField.get(String name, int val) method.

public abstract boolean get(String name, int val)

Parameters

  • name − The name of the field.

  • val − The default value to use if name does not have a value.

Return Value

This method returns the value of the named int field.

Exception

  • IOException − If there are I/O errors while reading from the underlying InputStream.

  • IllegalArgumentException − If type of name is not serializable or if the field type is incorrect.

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

The following example shows the usage of ObjectInputStream.getField get(String name, int 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 int var = 76458;
      
      // assign a new serialPersistentFields 
      private static final ObjectStreamField[] serialPersistentFields = {
         new ObjectStreamField("var", Integer.TYPE)
      };

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

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

         // get var
         var = (int) fields.get("var", 0);
      }

      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 −

76458

Example - Read a Serialized int Field when Field is Present

The following example shows the usage of ObjectInputStream.getField get(String name, int val) method. This example demonstrates reading a int field that was properly 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 = "person_int1.ser";

      // Serialize
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         Person person = new Person("Alice", 30);
         oos.writeObject(person);
         System.out.println("Person object serialized.");
      }

      // Deserialize
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         Person deserialized = (Person) ois.readObject();
         System.out.println("Deserialization complete.");
      }
   }

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

      String name;
      int age;

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

      private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField fields = ois.readFields();
         int age = fields.get("age", -1); // -1 is default if not found
         System.out.println("Age field value: " + age);  // Should print 30
      }
   }
}

Output

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

Person object serialized.
Age field value: 30
Deserialization complete.

Explanation

  • We serialize a class with an int field called age, then read it using GetField.get("age", defaultValue).

  • Since the field exists in the stream, the actual value is returned.

Example - Handling a Missing int Field

The following example shows the usage of ObjectInputStream.getField get(String name, int val) method. In this example, we don't write the temperature field, so during deserialization, the default value is returned.

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 = "person_fixed.ser";

      // Serialize object (simulating older version with missing 'age' field)
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         Person person = new Person("Bob");
         oos.writeObject(person); // writeObject will exclude 'age'
         System.out.println("Serialized without 'age' field.");
      }

      // Deserialize (simulating newer version expecting 'age')
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         Person p = (Person) ois.readObject();
      }
   }

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

      String name;
      int age = 25; // default in new version

      Person(String name) {
         this.name = name;
      }

      // Custom serialization - omit 'age'
      private void writeObject(ObjectOutputStream oos) throws IOException {
         ObjectOutputStream.PutField putFields = oos.putFields();
         putFields.put("name", name);
         // 'age' is intentionally left out
         oos.writeFields();
      }

      // Custom deserialization - try reading 'age'
      private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField fields = ois.readFields();
         name = (String) fields.get("name", "Unknown");
         age = fields.get("age", -1);

         if (fields.defaulted("age")) {
            System.out.println("Field 'age' was defaulted (not present in stream).");
         } else {
            System.out.println("Field 'age' was found: " + age);
         }
      }
   }
}

Output

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

Serialized without 'age' field.
Field 'age' was found: 0

Explanation

  • We simulate an old version by not serializing the age field.

  • On deserialization, field age gets a default value of 0.

java_io_objectinputstream.getfield.htm
Advertisements