You are asking about how to get the name of a variable, which you donβt need to get, because it is misleading and is actually not that important and almost does not exist in the compiled code. Instead, you should focus on getting references to objects, not variable names. If you need to associate an object with a string, then you need to use a Map, for example, HashMap<String, MyType> or HashMap<MyType, String> , depending on what you want to use as a key, but again do not put too much Dependence on variable names, since not finite variables can change links when the hat falls, and objects can refer to more than one variable.
For example, in the following code:
JButton b1 = new JButton("My Button"); JButton b2 = b1;
what variable name is the name? Both b1 and b2 belong to the same exact JButton object.
And here:
JButton b1 = new JButton("My Button"); b1 = new JButton("My Button 2");
What is the variable name for the first JButton object? Does it matter that the variable b1 does not apply to this source object?
Again, do not put your faith in variable names, as they often mislead you.
source share