I am writing some code and I am trying to use System.out.println()
to print the name of an object.
For example, with the code String foo = new String("Hi");
, I want to print out "foo
".
How do I do this?
Asked
Active
Viewed 52 times
0

WacfeldWang
- 25
- 6
-
1`System.out.println("foo");` – Elliott Frisch Mar 19 '16 at 23:21
-
@ElliottFrisch nice ! – Benoit Vanalderweireldt Mar 19 '16 at 23:21
-
Yes, but that's hard-coded, which is not good – WacfeldWang Mar 19 '16 at 23:22
-
@WacfeldWang But it has the advantage that it will work. – Elliott Frisch Mar 19 '16 at 23:22
-
1I think you should read this. http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem What are you trying to achieve? – Paul Boddington Mar 19 '16 at 23:25
-
1Possible duplicate of [Java Reflection: How to get the name of a variable?](http://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable) – scana Mar 19 '16 at 23:33
-
@WacfeldWang You _cannot_ do this in Java. – Louis Wasserman Mar 20 '16 at 00:02
2 Answers
2
You cannot do this, for multiple reasons. The simplest one is that one object can be referenced from multiple variables:
String foo = new String("Hi");
String bar = foo;
Now both foo
and bar
refer to the same String
object "Hi"
. There is no way to decide on a single identifier.
Names of local variables are, essentially, a compile-time artifact. Once the compiler is done, you cannot access these names without access to the debug information produced when you compile with -g:vars
compiler flag.

Community
- 1
- 1

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
0
It's not possible the object reference name you give is not available at runtime.

Benoit Vanalderweireldt
- 2,925
- 2
- 21
- 31