Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string in place of variable name

Tags:

java

variables

If you have a Java variable named xyz. Then later on I define a string which has the value of the named variable I want to play with.

String x="xyz";

How do I get Java to recognise that String x as a pointer to variable xyz?

An arbitrary example:

JButton a= new JButton();

Later on ...

String x="a";

I want to now say something like

JButton called string x.setPreferredSize(new Dimension(40,30));
like image 518
John Avatar asked Mar 01 '11 16:03

John


People also ask

How do you use a string as the name of a variable?

We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function. Parameter: variable_name is the name of the value.

Can a string be a variable name?

String Variables. EES supports numerical and string variables. A string variable is identified with a variable name that ends with the $ character. A string array variable has the $ character just before the left bracket that holds the array index.

Can I use a string as a variable in Java?

Variables are containers for storing data values. In Java, there are different types of variables, for example: String - stores text, such as "Hello". String values are surrounded by double quotes.

How do I print a variable name as a string?

To print a variable's name:Use a formatted string literal to get the variable's name and value. Split the string on the equal sign and get the variable's name. Use the print() function to print the variable's name.


2 Answers

In general, if you want to access a variable in this way, you have to use Reflection, which is slower and potentially dangerous.

However, since you have a very specific scenario in mind, I'd take a different approach. Why not put your buttons or other elements into a map, with keys that are strings:

Map<String, JComponent> currentComponents = new HashMap<String, JComponent>();

currentComponents.put("a", new JButton());

String x = "a";

currentComponents.get(x).setPreferredSize(new Dimension(40,30));
like image 55
Jacob Mattison Avatar answered Sep 19 '22 04:09

Jacob Mattison


The short answer is that you can't do something like this. That just isn't the way the Java language works. The long answer is that you might be able to simulate something using the Reflection API.

like image 42
Tony Casale Avatar answered Sep 22 '22 04:09

Tony Casale