How to get fields of an object using reflection in java

The example shows you how to get all the fields on an object using reflection in java.

Below using reflection to obtain the fields of an 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:

Below is the example which show how to get the fields of an object using reflection in java.

package com.java.connect.reflect;
 
import java.util.Date;
import java.lang.reflect.Field;
 
//How to get fields of an object on java
public class ReflectionFieldExample {
 
    public static void main(String[] args) {
        Employee object = new Employee();
        Class clazz = object.getClass();
        // You can get all object fields including
        // public, protected, package and private access fields.
        Field[] fields = clazz.getDeclaredFields();
        System.out.println("The class has " + fields.length + " total fields");
        for (Field field : fields) {
            System.out.println("The field name is : " + field.getName());
            System.out.println("The field type is : "
                    + field.getType().getName());
        }
        System.out.println("=====================================");
        // Get all public fields.
        fields = clazz.getFields();
        System.out.println("The class has " + fields.length + " public fields");
        for (Field field : fields) {
            System.out.println("The field name is : " + field.getName());
            System.out.println("The field type is : "
                    + field.getType().getName());
        }
        System.out.println("=====================================");
        try {
            // Get field name id with public access modifier
            Field field = clazz.getField("employeeId");
            System.out.println("The field name is : " + field.getName());
            System.out.println("The field type is : "
                    + field.getType().getName());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
 
class Employee {
    public Long employeeId;
    protected String name;
    private Date dob;
    Double weight;
 
    // Setter and getter
}

The output of the above example will be as:

The class has 4 total fields
The field name is : employeeId
The field type is : java.lang.Long
The field name is : name
The field type is : java.lang.String
The field name is : dob
The field type is : java.util.Date
The field name is : weight
The field type is : java.lang.Double
=====================================
The class has 1 public fields
The field name is : employeeId
The field type is : java.lang.Long
=====================================
The field name is : employeeId
The field type is : java.lang.Long