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
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.
You can use Component.setName() to give names to Swing and AWT components.
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:
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.