2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Reflection - How to get the name of a variable?

I have a class where some variables are declared.Now my requirement is to find out the

name of each variable from that class.

Code Snippet:

public class ClassOne{

    int var1;

    String var2;

    float var3;

    ...

}

userimage

I hope from the below snippet you can able to find out your answer which you looking for,

package com.kodetalk.test;

import java.lang.reflect.Field;

public class AccessVariableName {

 public int i = 10;

 public Integer test = 10;

 public String omghi = "PQR";

 public static String testStatic = "THIS IS STATIC";

 public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
  AccessVariableName accessVariableName = new AccessVariableName ();
  for(Field field : accessVariableName.getClass().getFields()) {
   System.out.println(field.getGenericType() +" "+field.getName() + " = " + field.get(accessVariableName));
  }
 }

}


Answer is