How do I get the name of a variable in Java?

Possible duplicate:
Java Reflection: how to get variable name?

I have found various discussions on this topic, but have never answered them.

A anyVariableName = new A();

      

How can I get the name of the variable anyVariableName

and get the string "anyVariableName"

in the result? Is this possible in Java?

+3


source to share


2 answers


If anyVariableName

is a local variable, you cannot. If this is a field, use Class#getField()

or Class#getDeclaredField()

.



+7


source


The only local names of local places are stored in source (which you can parse) or debug information (which you can get from bytecode if it was included)



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

+7


source







All Articles