How do I print the variable name holding an object?

前端 未结 10 1119
耶瑟儿~
耶瑟儿~ 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条回答
  •  萌比男神i
    2020-12-16 15:52

    Slightly more complete (but essentially the same as above):

    1. 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".
    2. 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.

提交回复
热议问题