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
  • 697,062
  • 78
  • 1,055
  • 1,465
0

It's not possible the object reference name you give is not available at runtime.

Benoit Vanalderweireldt
  • 2,853
  • 2
  • 19
  • 31