How do I get fields of a class object?

The example below using reflection to obtain the fields of a class object. We’ll get the field names and their corresponding type. There are three ways shown below which can be use to get an object fields:

  • Class.getDeclaredFields()
  • Class.getFields()
  • Class.getField(String)

package org.kodejava.example.lang;

import java.util.Date;
import java.lang.reflect.Field;

public class GetFields {
    public Long id;
    protected String name;
    private Date birthDate;
    Double weight;

    public static void main(String[] args) {
        GetFields object = new GetFields();
        Class clazz = object.getClass();

        //
        // Get all object fields including public, protected, package and private
        // access fields.
        //
        Field[] fields = clazz.getDeclaredFields();
        System.out.println("Number of fields = " + fields.length);
        for (Field field : fields) {
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        }

        System.out.println("n----------------------------------------n");
        
        //
        // Get all object accessible public fields.
        //
        fields = clazz.getFields();
        System.out.println("Number of fields = " + fields.length);
        for (Field field : fields) {
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        }

        System.out.println("n----------------------------------------n");

        try {
            //
            // Get field name id with public access modifier
            //
            Field field = clazz.getField("id");
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply