1

i need to call a function with the same var name but with a little different example:

private final String REQ_DROPDOWN_1 = "//div[text()='XXX']";
private final String REQ_DROPDOWN_2 = "//div[text()='YYY']";

public boolean goodVar(String num){
     return this.IsVisible(REQ_DROPDOWN_ + num);
}

How i Can use the name of the var dynamically

wolfenblut
  • 131
  • 1
  • 11
Tzahi
  • 259
  • 3
  • 12
  • 3
    Why not just put the values into a map or an array/list? (If you could change your parameter type from `String` to `int` that would make accessing a list simpler...) – Jon Skeet May 08 '22 at 06:32
  • we don't want to use hardcode Stringvalue because I use a lot of places in this String – Tzahi May 08 '22 at 06:36
  • 2
    I'm afraid I don't fully understand your comment, but if you're trying to rely on variable names, that *is* hard-coding the name. – Jon Skeet May 08 '22 at 06:44
  • Correct. The Java language doesn't support variables with runtime generated synthesized names. – Stephen C May 08 '22 at 06:46
  • Use data structures. Array, ArrayList, LinkedList, Queue, etc. – wolfenblut May 08 '22 at 07:31

1 Answers1

2

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();
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 2
    Note that currently this won't compile as `num` is a `String` - the OP will either need to change the parameter type to `int` or parse the string to an integer first. – Jon Skeet May 08 '22 at 06:45