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



Description

The Java ObjectInputStream.getField get(String name, Object val) method gets the value of the named Object field from the persistent field.

Declaration

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

public abstract Object get(String name, Object 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 Object 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, Object val) method

The following example shows the usage of ObjectInputStream.getField get(String name, Object 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 of a
         System.out.println("" + a.var);

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

   static public class Example implements Serializable {
      static Object var = "Hello World";
      
      // assign a new serialPersistentFields 
      private static final ObjectStreamField[] serialPersistentFields = {
         new ObjectStreamField("var", Object.class)
      };

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

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

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

      private void writeObject(ObjectOutputStream out) throws IOException {

         // write into the ObjectStreamField array the variable string
         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 −

Hello World

Example - Read a Serialized String Field when Field is Present

The following example shows the usage of ObjectInputStream.getField get(String name, Object val) method. This example demonstrates reading a string field that was properly serialized.

ObjectInputStreamDemo.java

package com.tutorialspoint;

import java.io.*;

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

      // Serialize with a 'city' field
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         Person person = new Person("Alice", "New York");
         oos.writeObject(person);
      }

      // Deserialize
      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;
      String city;

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

      private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField fields = ois.readFields();
         String cityVal = (String) fields.get("city", "Unknown");
         System.out.println("Deserialized city: " + cityVal);  // Output: New York
      }
   }
}

Output

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

Deserialized city: New York

Explanation

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

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

Example - Handling a Missing String Field

The following example shows the usage of ObjectInputStream.getField get(String name, string 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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectInputStreamDemo implements Serializable {
   public static void main(String[] args) throws Exception {
      // Serialize without department field
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
         oos.writeObject(new ObjectInputStreamDemo().new Employee());
      }

      // Deserialize
      try (ObjectInputStream ois = new ObjectInputStream(
         new ByteArrayInputStream(bos.toByteArray()))) {

         Employee emp = (Employee) ois.readObject();
         System.out.println("Department: " + emp.department); 
         // Output: Department: Unassigned
      }
   }
   class Employee implements Serializable{
      private String department;

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

         ObjectInputStream.GetField fields = in.readFields();
         this.department = (String) fields.get("department", "Unassigned");
      }
   }
}

Output

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

Department: null

Explanation

  • The get("department", "Unassigned") method looks for the "department" field in serialized data.

  • Since the field was not serialized, it has been assigned “null”. This is what shows in the deserialized output.

java_io_objectinputstream.getfield.htm
Advertisements