Get all declared fields from a class in Java


An array of field objects is returned by the method java.lang.Class.getDeclaredFields(). 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

package Test;
import java.lang.reflect.*;
public class Demo {
   int i;
   char c;
   public Demo(int i, char c) {
      this.i = i;
      this.c = c;
   }
   public static void main(String[] args) {
     try {
         Demo obj = new Demo(7, 'A');
         Class c = obj.getClass();
         Field[] fields = c.getDeclaredFields();
         for(int i = 0; i < fields.length; i++) {
           System.out.println("The field is: " + fields[i].toString());
         }
      } catch(Exception e) {
         System.out.println(e.toString());
      }
   }
}

Output

The field is: int Test.Demo.i
The field is: char Test.Demo.c

Now let us understand the above program.

An object of class Demo is created in the main() method. Then the array fields[] stores the field objects that are obtained using the method getDeclaredFields(). Then the fields are displayed using a for loop. A code snippet which demonstrates this is as follows −

Demo obj = new Demo(7, 'A');
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
for(int i = 0; i < fields.length; i++) {
   System.out.println("The field is: " + fields[i].toString());
}

Updated on: 25-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements