Programatically obtain name of a variable...

I would like to pass a variable to a method that prints the name of the variable as well as the value.

Given:

String foo ="bar";

publicvoid printInfo(foo){

...

}

Question:

How do I programatically obtain the name of the variable foo (which is of course foo)?

i.e.

Variable Name: foo

Variable Value: bar

[515 byte] By [rjea] at [2007-10-2 6:44:54]
# 1
Basically, you can't.If your variable is an object variable or a static class variable, you can use reflection to get a Field and get the name from that. Any local (stack) variable names disappear on compile.
tjacobs01a at 2007-7-16 13:53:25 > top of Java-index,Java Essentials,New To Java...
# 2
Take a look at java.lang.Class.getDeclaredField(name). You can determine the list of defined fields in a class via Class.getFields().- Saish
Saisha at 2007-7-16 13:53:25 > top of Java-index,Java Essentials,New To Java...
# 3
That's impossible, and you misunderstand how variables work in Java.Suppose you have a method: printVariableNameAndValue(String s)What should that method print if you'd call it with a literal value, for example: printVariableNameAndValue("hello") ?
jesperdja at 2007-7-16 13:53:25 > top of Java-index,Java Essentials,New To Java...
# 4
> What should that method print if you'd call it with a> literal value, for example:> printVariableNameAndValue("hello") ?Why, null, or perhaps the empty string, of course. :-)@OP: I'm just kidding. The others are right. There's no way to do it.
jverda at 2007-7-16 13:53:25 > top of Java-index,Java Essentials,New To Java...