How do I print the variable name holding an object?

前端 未结 10 1122
耶瑟儿~
耶瑟儿~ 2020-12-16 15:27

How do I print the variable name holding my object?

For example, I have:

myclass ob=new myclass()

How would I print \"ob\"?

10条回答
  •  情歌与酒
    2020-12-16 15:38

    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
    

提交回复
热议问题