How do I print the variable name holding an object?

前端 未结 10 1127
耶瑟儿~
耶瑟儿~ 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:44

    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());
    

提交回复
热议问题