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

后端 未结 9 1769
陌清茗
陌清茗 2020-12-10 05:30

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


There is a JPanel contains some JTextFields, a map contains all the JTextFields

相关标签:
9条回答
  • 2020-12-10 06:18

    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.

    0 讨论(0)
  • 2020-12-10 06:19

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

    0 讨论(0)
  • 2020-12-10 06:25

    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 A instance now? Is it "a"? Is it "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]?

    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:

    • 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.

    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.)

    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 JComponent hierarchy and set a name on any components as appropriate.

    0 讨论(0)
提交回复
热议问题