{

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


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

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

How to get variable name of an class java reflection API

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 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 getFields() method and private variables are not displayed.

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

Here is an example to retrive all fields of an 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.