8

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
  • 131
  • 1
  • 1
  • 8
  • 1
    What for do you need it? – Grim Jul 12 '14 at 06:59
  • Why not just use `"nameOfCar"`? – Henry Jul 12 '14 at 06:59
  • 2
    In Java, variable names are only available at compile time. They are not available when you run your program. – Code-Apprentice Jul 12 '14 at 07:00
  • @KorayTugay Of course it's possible. Reflection is there for a reason. (It's just slow.) –  Jul 12 '14 at 07:01
  • @TheLostMind Oh, sorry, then it isn't possible. I was thinking that the OP was talking about a field of a class. –  Jul 12 '14 at 07:23
  • So it is not like Python, variable.__name__. However, if you use mapping structure and store it inside statically, then you can display the variable name. – Ahx Jan 08 '19 at 11:27

2 Answers2

9

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
  • 232,312
  • 42
  • 391
  • 431
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
  • 63,511
  • 37
  • 265
  • 281