Java 如何打印保存对象的变量名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3959206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:35:47  来源:igfitidea点击:

How do I print the variable name holding an object?

java

提问by Bipin Sahoo

How do I print the variable name holding my object?

如何打印保存对象的变量名称?

For example, I have:

例如,我有:

myclass ob=new myclass()

How would I print "ob"?

我将如何打印“ob”?

采纳答案by Jon Skeet

Objects don't havenames, unless you happen to be using a class which allows each object to be given one (e.g. via a variable retrieved with getName()).

对象不具有名称,除非你碰巧使用的一类,它允许给予一个每一个对象(例如,通过与取回的变量getName())。

In particular, the name of any particular variable used to refer to an object is completely unknown to the object itself. So you can't do:

特别是,用于引用对象的任何特定变量的名称对于对象本身来说是完全未知的。所以你不能这样做:

Object foo = new Object();
// There's no support for this
String name = foo.getName(); // expecting to get "foo"

(Bear in mind that several variables could all refer to the same object, and there don't have to be anynamed variables referring to an object.)

(请记住,多个变量都可以引用同一个对象,并且不必有任何命名变量引用一个对象。)

回答by willcodejavaforfood

System.out.println();Is the command used to print out to the console.

System.out.println();是用来打印到控制台的命令。

So if you have your own class that you created and instantiated, you could do:

因此,如果您创建并实例化了自己的类,则可以执行以下操作:

MyObject obj = new MyObject();
System.out.println(obj);

and that would print out the toString()implementation of MyObject. The default implementation is not very interesting, so for useful info, you would have to override toString().

这将打印出toString()的实施MyObject。默认实现不是很有趣,因此要获得有用的信息,您必须覆盖toString().

回答by Tomas Narros

To print the object type name:

要打印对象类型名称:

System.out.println(myObject.getClass().getName());

回答by Tyler Treat

I'm assuming you want a way to "print" an object, in which case, you'll first want to override the toString()method for your object. This will allow you to specify what an object of your type returns when you call toString().

我假设您想要一种“打印”对象的方法,在这种情况下,您首先要覆盖toString()对象的方法。这将允许您指定您的类型的对象在您调用时返回的内容toString().

Then, you can simply do System.out.println(MyObject);

然后,你可以简单地做 System.out.println(MyObject);

This will implicitly call MyObject's toString().

这将隐式调用 MyObject 的toString().

回答by DwB

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".
  1. 如果你有一个对象:object.getClass().getName()会给你对象的完全限定名称(package.className。例如,String thing = new String(); thing.getClass().getName() 将返回“java.lang.String ”。
  2. 如果你有一个类名:className.class.getName()会给你对象的完全限定名(package.className。例如。String.class.getName() 将返回“java.lang.String”。

Print it how ever you want. Perhaps using System.out.println().

随心所欲地打印它。也许使用 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.

在大多数情况下,想要打印变量名称是一个荒谬的请求,但如果您确实需要这样做,请阅读 Java 调试信息。

回答by Khiet Nguyen

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

回答by Aashish Pawar

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

回答by B. Somersby

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.

这实现了所需的结果,但它有点虚伪,因为如果 toString() 返回的字符串实际上反映了您的变量的名称(当然,只有您知道,因为编码员会知道),您必须使用该方法在此实现中使用的约定,因为返回的字符串采用 ClassName+counter 格式,您必须使用该格式命名变量:myClass1、myClass2 等。如果您将变量命名为其他格式方式(例如 className+A/B/C 等或 someRandomVariableName)虽然返回字符串将保持由 toString() 方法实现,即返回 myClass1、myClass2 等,但它不会反映您实际使用的变量名称代码。

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

}

回答by JPNoyola

Try reflection + hash code. E.g.:

尝试反射 + 哈希码。例如:

String hashcode = ob.hashCode();
String obName;
java.lang.reflect.Field[] fields = 
ob.getClass().getDeclaredFields();

for( final  java.lang.reflect.Field field : fields )
{
  if( field.hashCode().equals(hashcode) )
  {
    obName = field.getName();
    break;
  }
}
System.out.println(obName);

回答by saravana

import java.lang.reflect.*;

public class myclass {
    private myclass ob;

    public static void main(String args[]) {
            Field fd[] = myclass.class.getDeclaredFields();
            for (int i = 0; i < fd.length; i++) {
                  System.out.println(fd[i].getName());
            }
    }
}