Java - ObjectInputStream.GetField defaulted() method



Description

The Java ObjectInputStream.getField defaulted(String name) method checks whether a field was explicitly written to the stream or not. It returns true if the field was not written (i.e., default value will be used), otherwise false.

Declaration

Following is the declaration for java.io.ObjectInputStream.getField.defaulted() method.

public abstract boolean defaulted(String name)

Parameters

name − The name of the field.

Return Value

This method returns true, if and only if the named field is defaulted.

Exception

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

  • IllegalArgumentException − If name does not correspond to a serializable field.

Example - Usage of ObjectInputStream.getField defaulted() method

The following example shows the usage of ObjectInputStream.getField defaulted() 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();

         // get if variable string is default in Example class
         System.out.println("" + a.isDefault);

         // print the string of a
         System.out.println("" + a.string);

      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }

   static public class Example implements Serializable {
      static String string = "Hello World!";
      static boolean isDefault;
	  
      // assign a new serialPersistentFields 
      private static final ObjectStreamField[] serialPersistentFields = {
         new ObjectStreamField("string", String.class)
      };

      // create a custom readObject method
      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
         isDefault = fields.defaulted("string");
         string = (String) fields.get("string", null);
      }
	  
      // create a custom writeObject method
      private void writeObject(ObjectOutputStream out) throws IOException {

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

Output

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

false
Hello World!

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 - Not serializing transient 'password' field

The following example shows the usage of ObjectInputStream.getField defaulted() method.

ObjectInputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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) {
      try {
         // Serialize
         Person original = new Person("Alice", 30, "secret123");
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(original);
         oos.close();

         // Modify the serialized data to remove the age field
         byte[] data = baos.toByteArray();
         // In a real scenario, you might read from a file where the field was missing

         // Deserialize
         ByteArrayInputStream bais = new ByteArrayInputStream(data);
         ObjectInputStream ois = new ObjectInputStream(bais);
         Person deserialized = (Person) ois.readObject();

         System.out.println("Deserialized: " + deserialized);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   static class Person implements Serializable {
      private String name;
      private int age;
      private transient String password; // Not serialized

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

      // Custom serialization
      private void writeObject(ObjectOutputStream out) throws IOException {
         ObjectOutputStream.PutField fields = out.putFields();
         fields.put("name", name);
         fields.put("age", age);
         // password is transient, so not included
         out.writeFields();
      }

      // Custom deserialization
      private void readObject(ObjectInputStream in) 
         throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField fields = in.readFields();

         name = (String) fields.get("name", null);

         // Check if age was in the stream
         if (fields.defaulted("age")) {
            System.out.println("Age field was defaulted - using default value 0");
            age = 0; // Default value
         } else {
            age = fields.get("age", 0);
         }

         // password is transient and won't be in the stream
         password = "defaultPassword";
      }

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

Output

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

Deserialized: Person{name='Alice', age=30, password='defaultPassword'} 

Explanation

  • Person object is serialized, and later de-serialized.

  • The transient field "password" is never in the stream (always defaulted)

java_io_objectinputstream.getfield.htm
Advertisements