Lets say i have a a button somewhere in the code: \"JButton closeButton\". I dont know that it\'s called \"closeButton\" but that\'s what i want to find out.
At run
import java.lang.reflect.*;
public class field1 {
private double d;
public static final int i = 37;
String s = "testing";
public static void main(String args[])
{
try {
Class cls = Class.forName("field1");
Field fieldlist[]
= cls.getDeclaredFields();
for (int i
= 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
System.out.println("name
= " + fld.getName());
System.out.println("decl class = " +
fld.getDeclaringClass());
System.out.println("type
= " + fld.getType());
int mod = fld.getModifiers();
System.out.println("modifiers = " +
Modifier.toString(mod));
System.out.println("-----");
}
}
catch (Throwable e) {
System.err.println(e);
}
}
}
This should give you a list of all the fields of the class.
If your "variable" is a field, then the solution using reflection (mentioned in another answer) works.
If your variable is a local variable, you can in theory use a JVMTI agent to get its name, provided that you compiled your class with debug info. And that your local variable is in scope when you check. And that nobody changed its value and there's no other variable with the same value (in which case you couldn't decide which is the one you need).
However, you should absolutely not do any of them. They are theoretical possibilities, akin to punching yourself so hard that you pass out.
I think you have 2 ways:
Short answer: it is not possible.
Details: What you call name
has in fact nothing to do with the instance of JButton
. It's just the variable that holds the referece of which allows to acces this instance at runtime. This sample code will show this mor evidently:
JButton newButton = new JButton();
JButton otherButton = newButton;
Here both variables holds a reference to teh same instance of JButton.