Get the list of all the public fields in Java

Java 8Object Oriented ProgrammingProgramming

An array of field objects is returned by the method java.lang.Class.getFields(). These field objects include the accessible public fields of the class that is represented by the class object.

Also, the getFields() method returns a zero length array if the class or interface has no public fields that are accessible 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.Thread.class;
      Field[] fields = c.getFields();
      for(int i = 0; i < fields.length; i++) {
         System.out.println("The Field is: " + fields[i].toString());
      }
   }
}

Output

The Field is: public static final int java.lang.Thread.MIN_PRIORITY
The Field is: public static final int java.lang.Thread.NORM_PRIORITY
The Field is: public static final int java.lang.Thread.

Now let us understand the above program.

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

Class c = java.lang.Thread.class;
Field[] fields = c.getFields();
for(int i = 0; i < fields.length; i++) {
   System.out.println("The Field is: " + fields[i].toString());
}
raja
Published on 08-Jan-2019 16:07:23
Advertisements