ObjectStreamClass getFields() in Java

getFields(): This method is available in the java.io.ObjectStreamClass class of Java.

Syntax:

ObjectStreamField[] java.io.ObjectStreamClass.getFields()

This method returns an array of the fields of this serializable class.

Parameters: NA

Returns: an array containing an element for each persistent field of this class.

Note: Returns an array of length zero if there are no fields.

Exceptions: NA

Approach 1: When an empty array is a return

Java

import java.io.ObjectStreamClass;
import java.util.Arrays;

public class ObjectStreamClassgetFields {
    public static void main(String[] args) {

        ObjectStreamClass objectStreamClass =
ObjectStreamClass.lookup(String.class);

        System.out.println(Arrays.toString(objectStreamClass.getFields()));
    }
}

Output:

[]


Approach 2: When some fields are returned

Java

import java.io.ObjectStreamClass;
import java.util.ArrayList;
import java.util.Arrays;

public class ObjectStreamClassgetFields {
    public static void main(String[] args) {

        ObjectStreamClass objectStreamClass =
ObjectStreamClass.lookup(ArrayList.class);

        System.out.println(Arrays.toString(objectStreamClass.getFields()));
    }
}

Output:

[I size]


Some more methods of ObjectStreamClass

forClass()This method returns the class to the local VM that this version is mapped to.

getField(String)This method gets the field of this class by name.

getName()This method returns the name of the class described by this descriptor.

getSerialVersionUID()This method returns the serialVersionUID for this class.

lookup(Class)This method creates an ObjectStreamClass instance if one does not exist yet for the class.

lookupAny(Class)This method returns the descriptor for any class, regardless of whether it implements Serializable.

toString()This method returns a string describing this ObjectStreamClass.

No comments:

Post a Comment