How do I print the variable name holding my object?
For example, I have:
myclass ob=new myclass()
How would I print \"ob\"?
You can't get the name of object reference. Instead you can get its hashcode or counter. I solve this problem as follows:
class ObjectName
{
static int num;
ObjectName()
{
num++;
}
public int getObjectCount()
{
return num;
}
public static void main(String[] args) {
ObjectName ob1=new ObjectName();
System.out.println(ob1.getClass().getName()+" "+ob1.getObjectCount());
ObjectName ob2=new ObjectName();
System.out.println(ob1.getClass().getName()+" "+ob1.getObjectCount());
}
}
Output:
ObjectName 1
ObjectName 2