How to get variable name in java class example| getDeclaredFields reflection

In this example, How to get variable names of a class using reflection.

Reflection package API in java provides to analyze and update behavior of java classes at runtime.

class or interface in java contains variables declared with different types and modifiers - public, final, private, default, protected, and static.

getFields() method of an java.lang.Class gives list of all public aviable variable names of an interface or class in java.

here is an example of using the getFields method


import java.lang.reflect.Field;


public class Main {
    private Integer privateVariable = 1;

    public Integer value = 1;

    public String str = "helloworld";

    public static String staticValue = "THIS IS STATIC";
    public static final String finalValue = "THIS IS STATIC";

    public static void main(String[] args) {
        Main main= new Main();

        Class class = main.getClass();
        Field[] fields = class.getFields();
        for(Field f: fields){
            System.out.println(f.getName());
        }
    }
}

Here is the output

value
str
staticValue
finalValue

As you see, only public variable names are retrieved using the getFields() method, and private variables are not displayed.

How to retrieve private variable names of a class? getDeclaredFields() method of an class returns public ,protected, default and private variable of an class or interface.

Here is an example to retrieve all fields of a java class

import java.lang.reflect.Field;


public class Main {
    private Integer privateVariable = 1;

    public Integer value = 1;

    public String str = "helloworld";

    public static String staticValue = "THIS IS STATIC";
    public static final String finalValue = "THIS IS STATIC";

    public static void main(String[] args) {
        Main main= new Main();

        Class myclass = main.getClass();
        Field[] fields = myclass.getDeclaredFields();
        for(Field f: fields){
            System.out.println(f.getName());
        }
    }
}

Output:

privateVariable
value
str
staticValue
finalValue