Assigning Variables With Dynamic Names in Java

Assigning variables with dynamic names in Java

This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.

Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.

int n[] = new int[3];
for (int i = 0; i < 3; i++) {
n[i] = 5;
}

List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
n.add(5);
}

Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
n.put("n" + i, 5);
}

It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.

However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.


1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!

How to create variables dynamically in Java?

A Map allows you to relate any key with any value. In this case, the key is the name of the variable, and the value is the value

Map<String, String> details = new HashMap<>();
for (int i = 1; i <101; i++) {
if (i<60) {
details.put("person" + i, "female");
}
else {
details.put("person" + i, "male");
}
}

create variables dynamically, Data Types of java Variables

You can not create dynamic variables in Java because Java isn't a scripting language. YOu need to create variables in source code. But Java provides other ways to do this.
You can use arrays or Map<String, String> etc for this purpose.

Map<String, String> map= new HashMap<>(); 
int i=0;
while(true) {
// you can use whatever condition you need
details.put("key" + i, "val: "+i);
i++
// some condition to break the loop
}

Dynamic variable declaration in Java

SOAPElement[] userid = new SOAPElement[userids.length]
for(int i=0; i<userids.length; i++){
userid[i] = example.addChildElement("userid");
userid[i].addTextNode(userids[i]);
}

'userid+i' is not an acceptable java variable name (identifier) so you must be getting a compile time error like i cannot be resolved to a variable.

Better approach is to use an array of values, you can use an array of SOAPElement objects as I have listed above or other (Like List) Implementations of java Collections

Also read valid java identifier rules

How to use var name dynamically in [java]

The simplest solution is this:

private final String[] REQ_DROPDOWNS = {
"//div[text()='XXX']", "//div[text()='YYY']"};

// NB: I have changed the argument type to 'int'
public Boolean goodVar(int num) {
if (num > 0 && num < REQ_DROPDOWNS.length) {
return this.IsVisble(REQ_DROPDOWNS[num - 1]);
} else {
throw new IllegalArgumentException("Num out of range: " + num);
}
}

Java does not support dynamic variables; see https://stackoverflow.com/questions/6729605.

You could dynamically lookup a Field and then access it using reflection, but it is more complicated and error prone to do that.

You could also use a HashMap, but that too is unnecessarily complicated for the use-case in your example. But if you wanted the name lookup to be more flexible, this would be a good option.

private final Map<String, String> map = new HashMap<>(){{
put("REQ_DROPDOWN_1", "//div[text()='XXX']");
put("REQ_DROPDOWN_2", "//div[text()='YYY']");
}}

public Boolean goodVar(String suffix) {
String path = map.get("REQ_DROPDOWN_" + suffix);
if (path == null) {
throw new IllegalArgumentException("Unknown suffix: " + suffix);
}
return this.IsVisble();
}

How to instantiate variable with name from a string?

Reflection views class & field definitions, and enables you to instantiate classes dynamically (by a variable name). It does not allow you to dynamically define fields or classes.

As Hovercraft says, you probably want a reference.

Using a variable enables you to reference the object you want, then set the existing 'property'/ or apply the behavior you want on that.

For example:

public void setupJFrame (JFrame frame, boolean maximize) {
if (maximize) {
frame.setExtendedState( frame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
} else {
frame.setLocationRelativeTo(null);
}
}

If you need to know on the 'JFrame' what state it is in, you could either subclass it to add a property storing that, or (perhaps better) just make a 'getter' or static 'getter' utility method to answer this using it's existing state.

public static boolean isFrameMaximized (JFrame frame) {
if ((frame.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH)
return true;
return false;
}


Related Topics



Leave a reply



Submit