10

is possible get variable name?

For example:

String nameOfCar = "audi";

Now print the result:

System.out.println(nameOfCar.getVname???or something similar);

Screen:

nameOfCar
user3784463
  • 151
  • 1
  • 1
  • 9

2 Answers2

11

You can get all field name by reflection

Class yourClass = YourClass.class
Field[] fields = yourClass.getFields();
for(Field f: fields){
    f.getName();
}

or if you want mapping then go for Map

Map<String, String> propertyToValueMap

if you are trying to read method's local variable name, then it is not that simple to fetch also a signal that you are doing something wrong

jmj
  • 237,923
  • 42
  • 401
  • 438
0

You can do it via reflection

Class  myClass = MyClass.class
Field field = myClass.getField("nameOfCar ");
System.out.println(field .getName());

To get all the fields without using the name you can do

Field[] myFields = myClass .getFields();
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289