How do I print the variable name holding an object?

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

    This achieves the required result, but it is a bit of a fudge, in that if the string returned by toString() is to actually reflect the name of your variable (which of course, only you, as the coder will know), you have to use the convention that the method uses i.e. in this implementation, because the returned string is in the format ClassName+counter, you have to name your variable using that format: myClass1, myClass2, etc. If you name your variable in some other way (e.g. className+A/B/C etc or someRandomVariableName) although the return string would remain as implemented by the toString() method i.e. returning myClass1, myClass2, etc, it wouldn't reflect the variable name you have actually used in your code.

    class myClass {
    
        private static int counter = 1;
        private String string;
        private int objCounter;
    
        myClass(String string) {
            this.string = new String(string);
            objCounter = counter;
            counter++;
        }
    
        @Override
        public String toString() {
            return this.getClass().getName() + objCounter + ": " + this.string;
        }
    
        public static void main(String[] args) {
            myClass myClass1 = new myClass("This is the text for the first object.");
            myClass myClass2 = new myClass("This is the text for the second object.");
            System.out.println(myClass1);
            System.out.println(myClass2);
        }
    
    }
    

提交回复
热议问题