3

Possible Duplicate:
Java Reflection: How to get the name of a variable?

I've found various discussions on this topic but never any satisfying answer..

A anyVariableName = new A();

How can I get the name of the variable anyVariableName and get string "anyVariableName" as a result? Is this possible in Java?

Community
  • 1
  • 1
Wally_the_Walrus
  • 219
  • 1
  • 5
  • 17

2 Answers2

7

If anyVariableName is a local variable, you can't. If it's a field, use Class#getField() or Class#getDeclaredField().

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
7

The only places local variable names are stored is in the source (which you can parse) or the debug information (which you can get from the byte code if it has been included)

If it's a field you can use Class.getDeclaredFields() if you don't know the name.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • +1, If you get a Java "decompiler" and use it on a class you'll see all of your variables have changed names. For example, if you have `Socket s = new Socket(9001);` in your source you will likely see something like `Socket localSocket = new Socket(9001);`. Though this confuses me as I don't understand how reflection works if this sort of thing happens. – ldam Jan 22 '13 at 13:44
  • AFAIK, decompiler don't use the debug information. I am not sure why this is. – Peter Lawrey Jan 22 '13 at 14:19