Bipin Sahoo Bipin Sahoo - 4 months ago 21
Java Question

How do I print the variable name holding an object?

How do I print the variable name holding my object?

For example, I have:

myclass ob=new myclass()

How would I print "ob"?


Objects don't have names, unless you happen to be using a class which allows each object to be given one (e.g. via a variable retrieved with getName()).

In particular, the name of any particular variable used to refer to an object is completely unknown to the object itself. So you can't do:

Object foo = new Object();
// There's no support for this
String name = foo.getName(); // expecting to get "foo"

(Bear in mind that several variables could all refer to the same object, and there don't have to be any named variables referring to an object.)