Get all fields/data members of class in java (example)

By | March 23, 2017
  • Given a class in java containing public,private & protected fields.
  • Get/list/print all fields of class using class Class.
    • We will use getDeclaredFields() of Class to retrieve all data members.
Method Name Description
Field[] getDeclaredFields() Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

1. Program: print/list all fields/data members of class in java (example)

package org.learn.classes;

import java.lang.reflect.Field;

class Student {
    private String name;
    private int standard;
    protected String age;
    public float gender;

    public Student(String name, String age, float gender, int standard) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.standard = standard;
    }

    public String getName() {
        return name;
    }
}

public class DemoListAllFieldsOfClass {
    public static void main(String[] args) {
        Field[] fields = Student.class.getDeclaredFields();
        int nField = 1;
        System.out.println("1. List of all fields in a Student class");
        for (Field field : fields) {
            System.out.printf("%d. %s",++nField,field);
            System.out.println();
        }
        System.out.printf("%d. End - all fields of Student class",++nField);
    }
}

2. Output: print/list all fields/data members of class in java (example)

 1. List of all fields in a Student class
2. private java.lang.String org.learn.classes.Student.name
3. private int org.learn.classes.Student.standard
4. protected java.lang.String org.learn.classes.Student.age
5. public float org.learn.classes.Student.gender
6. End - all fields of Student class