1

I'm facing following problem: I have to give names to many thousands of GUI-Elements. Would be nice if it could work a script like:

JMenuItem myMenuItem = new JMenuItem();
myMenuItem .setName(this.getClass().getSimplename() + "." + myMenuItem .get??)

Would be nice if I could set the name of the element to "Classname.myMenuItem".

Is there any way to get the name (variable name ofc, not JMenuItem.getName()) of the variable?

SWYM
  • 43
  • 1
  • 8
  • Yes, use reflection for that. – Shark Feb 12 '16 at 08:55
  • 1
    A menu item instance could be referenced by multiple variables. Or it could be referenced by no variables. Which variable's name would it use in these cases? – Andy Turner Feb 12 '16 at 08:58
  • No... That's not possible... You should also avoid using `getClass().getSimplename()` for this... If you application is obfuscated, there's high chance that the class will be renamed to random alphabets... – Codebender Feb 12 '16 at 08:58

2 Answers2

0

You can do this for field via reflection: see Field.getName().

You cannot do it for local variable, they basically don't have any name after the code is compiled (well, in debug info they have but it's not easily accessible and understandable unless you implement debugger :-) ).

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
0

What you want is not possible. Even if some information about variable names is present in the class file, you still have to remember that there is a difference between the variable and the object it refers to. There can be any number of variables (local variables, member variables, parameters, etc) that refer to the same object. Keeping track of the names of all of those variables would impose too much of a run-time overhead.

Hoopje
  • 12,677
  • 8
  • 34
  • 50