Get the list of all declared fields in Java

Java 8Object Oriented ProgrammingProgramming

The list of all declared fields can be obtained using the java.lang.Class.getDeclaredFields() method as it returns an array of field objects. These field objects include the objects with the public, private, protected and default access but not the inherited fields.

Also, the getDeclaredFields() method returns a zero length array if the class or interface has no declared fields or if a primitive type, array class or void is represented in the Class object.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.lang.reflect.*;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Class c = java.lang.String.class;
      Field[] fields = c.getDeclaredFields();
      for(int i = 0; i < fields.length; i++) {
         System.out.println("The Field is: " + fields[i].toString());
      }
   }
}

Output

The Field is: private final char[] java.lang.String.value The Field is: private int java.lang.String.hash The Field is: private static final long java.lang.String.serialVersionUID The Field is: private static final java.io.ObjectStreamField[] java.lang.String.serialPersistentFields The Field is: public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER

Now let us understand the above program.

The class c holds the java.lang.String.class.. Then the array fields[] stores the field objects of this class that are obtained using the method getDeclaredFields(). Then the fields are displayed using the for loop. A code snippet which demonstrates this is as follows −

Class c = java.lang.String.class;
Field[] fields = c.getDeclaredFields();
for(int i = 0; i < fields.length; i++) {
   System.out.println("The Field is: " + fields[i].toString());
}
raja
Published on 09-Jan-2019 11:05:24
Advertisements