如何在java中获取对象的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2894127/
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-13 14:11:21  来源:igfitidea点击:

How can I get an Object's name in java?

java

提问by Hyman Ma

like this, A a = new A(), how can I get a's name?(Get a String "a" from a) ?

像这样,A a = new A(),我怎样才能得到 a 的名字?(从 a 中得到一个字符串“a”)?



There is a JPanel contains some JTextFields, a map contains all the JTextFields' names(the variables' names). I want to set the map's values to the JTextFields' texts.

有一个 JPanel 包含一些 JTextFields,一个映射包含所有 JTextFields 的名称(变量的名称)。我想将地图的值设置为 JTextFields 的文本。

public void mapToJPanel(Map map, JPanel panel) {
    Component[] compArr = panel.getComponents();
    for (Component comp : compArr) {
        if (comp.getClass().getSimpleName().equals("JTextField")) {
            JTextField textField = (JTextField) comp;
            textField.setText(map.get(textField.getName()).toString());//getName() method
        }
    }
}

Accross getName() method, I get null -_- I know the getName() method is not used to get the variable name. I'm using netbeans doing Java swing visual development , so I can not rewrite the components(like JTextField).

通过 getName() 方法,我得到 null -_- 我知道 getName() 方法不用于获取变量名称。我正在使用 netbeans 进行 Java swing 可视化开发,因此我无法重写组件(如 JTextField)。

采纳答案by Michael Borgwardt

You can use Component.setName()to give names to Swing and AWT components.

您可以使用Component.setName()为 Swing 和 AWT 组件命名。

回答by Chris

You can't.

你不能。

If you compile with debug symbols then the .class file will contain a table of variable names (which is how debuggers map variables back to your source code), but there's no guarantee this will be there and it's not exposed in the runtime.

如果您使用调试符号进行编译,那么 .class 文件将包含一个变量名称表(这是调试器将变量映射回源代码的方式),但不能保证它会存在并且不会在运行时中公开。

回答by Michael Aaron Safyan

While you can easily get the name of a variable's class by invoking .getClass().getCanonicalName() or .getClass().getSimpleName() (depending on whether you want the fully qualified name), it is not so easy to get the name of a variable. Java bytecode does not need to preserve the names of local variables (which are represented using push/pop operations on the stack); however, Java bytecode may contain the original names in comments. So, you might try reading the .class files from the .jar files and attempt to extract the variable names from the .class files, assuming that the compiler has included them as comments. As for member variables (i.e. fields), you can use reflection to get a class's field names.

虽然您可以通过调用 .getClass().getCanonicalName() 或 .getClass().getSimpleName()(取决于您是否想要完全限定名称)轻松获取变量类的名称,但获取变量名。Java 字节码不需要保留局部变量的名称(在堆栈上使用 push/pop 操作表示);然而,Java 字节码可能在注释中包含原始名称。因此,您可以尝试从 .jar 文件中读取 .class 文件并尝试从 .class 文件中提取变量名,假设编译器已将它们作为注释包含在内。至于成员变量(即字段),可以使用反射来获取类的字段名。

回答by labratmatt

You can't and it seems like you're doing something wrong if you need to do this. However, if you really want to pursue the logic you've outlined, why don't you do the following:

你不能,如果你需要这样做,你似乎做错了什么。但是,如果您真的想追求您概述的逻辑,为什么不执行以下操作:

Add a String member to A and in a constructor, assign it. Something like this:

将 String 成员添加到 A 并在构造函数中分配它。像这样的东西:

 A a = new A('a');

回答by Stephen C

You cannot, because an object does not have a name. Consider the following for example:

您不能,因为对象没有名称。例如,考虑以下内容:

A a = new A();
A b = a;

What is the "name" of the Ainstance now? Is it "a"? Is it "b"?

A现在实例的“名称”是什么?是"a"吗?是"b"吗?

And what about this?

而这个呢?

A[] a = new A[] { new A(), new A()};
a[0] = a[1];

What is the "name" of the instance at a[1]?

实例的“名称”是a[1]什么?

My point is that you cannot come up with a useful / usable definition of a universal Java object name that works in a wide range of contexts. Roadblock issues include:

我的观点是,您无法提出适用于广泛上下文的通用 Java 对象名称的有用/可用定义。路障问题包括:

  • Name stability: a "name" that changes when an object's reference is assigned is not useful.
  • Single name: an object should not simultaneously have multiple names.
  • Implementability: any naming system would have to be implementable without imposing a performance cost on normal usage of objects. AFAIK, this is impossible ... at least on the kind of hardware we currently use.
  • 名称稳定性:在分配对象的引用时更改的“名称”没有用。
  • 单一名称:一个对象不应同时具有多个名称。
  • 可实施性:任何命名系统都必须是可实施的,而不会对对象的正常使用造成性能成本。AFAIK,这是不可能的......至少在我们目前使用的那种硬件上。

The closest that Java comes to a name for an object is the object's "identity hashcode" value. It is not unique, but it has the property that it won't change for the lifetime of the object in the current JVM. (But even the identity hashcode comes at a runtime cost ... which makes it a Java design mistake in some peoples' view.)

Java 最接近对象名称的是对象的“身份哈希码”值。它不是唯一的,但它具有在当前 JVM 中对象的生命周期内不会更改的属性。(但即使是身份哈希码也有运行时成本......这在某些人看来是一个 Java 设计错误。)

The sensible approach to naming objects is (as others have said) to add "name" fields to the relevant classes (or use an existing one) and manage the names yourself as required.

命名对象的明智方法是(正如其他人所说)将“名称”字段添加到相关类(或使用现有类)并根据需要自己管理名称。



In the more specific case where the "object" is actually a JComponent, a given component cannot be relied on to have a name. (The getName()method can return null.) However, if you wanted to, you could traverse any JComponenthierarchy and set a name on any components as appropriate.

在“对象”实际上是 a 的更具体的情况下,JComponent不能依赖给定的组件具有名称。(该getName()方法可以返回null。)但是,如果您愿意,您可以遍历任何JComponent层次结构并根据需要在任何组件上设置名称。

回答by guthrie

The replication of the name (symbol) a is what is inconvenient and a bit noisy. In a language with macros, one could define this so that the copying would be automatic in the source code program.

名称(符号) a 的复制是不方便且有点嘈杂的。在带有宏的语言中,可以定义它,以便在源代码程序中自动复制。

make(A, a);

or makeA(a)

或 makeA(a)

回答by Chris Middleton

You can try defining a new Object which extends (either explicitly or just in function) the original Object with a new String field for the name of the Object. Then provide methods for getting that name when you need it. That approach has worked fairly well for me.

您可以尝试定义一个新对象,该对象使用对象名称的新字符串字段扩展(显式或仅在函数中)原始对象。然后在需要时提供获取该名称的方法。这种方法对我来说效果很好。

回答by Chris Middleton

You can always create name variable in the object's class, and use that variable beside others to pass information about this object.

您始终可以在对象的类中创建名称变量,并在其他变量旁边使用该变量来传递有关此对象的信息。

回答by karanalpe

I had the same problem, look that solution...

我有同样的问题,看看那个解决方案......

    DocumentoMB mb = new DocumentoMB();
    System.out.println(mb.getClass().getSimpleName());