0

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?

2 Answers2

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