This is only possible if the object you're trying to get is a class variable (defined outside of a method, as a part of the class).
You can then use Java's Reflection API to access the value of a field by the field name. The code for achieving this will look as follows:
public class Example {
public JButton foo_bar = new JButton("I am a Button");
public void fieldByNameExample() throws NoSuchFieldException, IllegalAccessException {
// The two parts we're going to concatenate to make "foo_bar"
String partA = "foo";
String partB = "bar";
// Gets the Field object representing the field by its name.
Field field = Example.class.getDeclaredField(partA + "_" + partB);
// Retrieves the contents of the Field for this object.
JButton value = (JButton) field.get(this);
System.out.println(value.getText()); // prints: "I am a Button"
}
}
You need to catch NoSuchFieldException
(thrown when no field with the given name exists), and IllegalAccessException
(thrown when the field you're trying to get the contents of is not accessible in the current context) when you call the above method.
As mentioned before, this only works if the variable is declared as a field in the class. It is not possible with variables declared inside methods (as the compiler discards the names of such local variables in the compilation process).
Please note that the Reflection API can be relatively slow, and using it is often not the best solution. You should also look into other solutions for your problem. If you still insist on using Reflection, I advise you to first look into documentation regarding Java Reflection, since the Reflection API is rather difficult to use if you don't know exactly what you're doing.