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



Description

The Java ObjectInputStream.getField get(String name, long val) method gets the value of the named long 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, long val) method.

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

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

      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 long Field when Field is Present

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

      // Serialize
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         Data data = new Data(123456789L);
         oos.writeObject(data);
         System.out.println("Data serialized.");
      }

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

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

      Data(long timestamp) {
         this.timestamp = timestamp;
      }

      private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField fields = ois.readFields();
         timestamp = fields.get("timestamp", -1L);
         System.out.println("Deserialized timestamp: " + timestamp);
      }
   }
}

Output

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

Data serialized.
Deserialized timestamp: 123456789

Explanation

  • get("timestamp", -1L) retrieves the value of the timestamp field.

  • Since the field exists, you'll get the actual serialized value (123456789L).

Example - Handling a Missing long Field

The following example shows the usage of ObjectInputStream.getField get(String name, long val) method. In this example, we don't write the age 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;
      long age = 25L; // 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", -1L);

         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

  • Retrieves long field "age" from serialized data. Since age doesn't exist, defaults to value "0".

java_io_objectinputstream.getfield.htm
Advertisements