How do I print the variable name holding an object?
To print the object type name:
System.out.println(myObject.getClass().getName());
Slightly more complete (but essentially the same as above):
-
If you have an object:
object.getClass().getName()
will give you the fully qualified name of the object (i.e.package.className. For example, String thing = new String(); thing.getClass().getName() will return "java.lang.String". -
If you have a class name:
className.class.getName()
will give you the fully qualified name of the object (i.e.package.className. For example. String.class.getName() will return "java.lang.String".
Print it how ever you want. Perhaps using System.out.println().
The name of the variable is compile time information that is not typically stored after compilation. The variable name is stored if you compile with debugging information.
In mamy contexts, it is a ridiculous request to want to print the name of a variable, but if you really need to do that, read up on java debugging information.
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.)
Workaround. If you want the object name then you can initialize at constructor.
//in class myClass
private String objName;
myClass(String objN)
{
this.objName = objN;
..
}
public String getObjName() {
return objName;
}
//in main()
.
.
.
myclass ob = new myclass("ob"); //any other variables accessing this object
//eg. temOb = ob get the same object name "ob"
System.out.println("object name is: " + ob.getObjName());
myclass ob1 = new myclass("ob1");
System.out.println("object name is: " + ob1.getObjName());