Reputation: 642
Here is an example of a string
expression I am creating that I then want to use in the condition of an if
statement.
public static String dynamicIf(String a, String b, String c){
String expression = "";
String[] list = {"one", "two", ""};
if(!a.equals(""))
expression += "a.equals(list[0])";
if(!b.equals(""))
{
if(!expression.equals(""))
expression += " && b.equals(list[1])";
else
expression += "b.equals(list[1])";
}
if(!c.equals(""))
{
if(!expression.equals(""))
expression += " && c.equals(list[2])";
else
expression += "c.equals(list[2])";
}
//String[] splitExpression = expression.split(" && ");
return expression;
}
So the function above creates a string which i would then like to use in the condition of an if
statement. The result of the method running with these parameters:
dynamicIf("one","two","");
is
a.equals(list[0]) && b.equals(list[1])
How can I get this expression in a string to run within the condition of an if
?
I hope you understand. Thank you.
Upvotes: 1
Views: 9802
Reputation: 1736
You can't do this in Java, as it is not an interpreted language. Instead, redesign your code. Something like this might get you on the right track:
public static boolean dynamicIf(String a, String b, String c) {
final String[] list = {"one", "two", ""};
boolean value = true;
if (!a.isEmpty()) {
value &= a.equals(list[0]);
}
if(!b.isEmpty()) {
value &= b.equals(list[1]);
}
if (!c.isEmpty()) {
value &= c.equals(list[2]);
}
return value;
}
This should give you the same results you're looking for. Example:
if (dynamicIf("one", "two", "")) // true
if (dynamicIf("", "two", "")) // true
if (dynamicIf("", "", "")) // true
if (dynamicIf("one", "two", "three")) // false
Edit: This may or may not be what you're looking for. You've left a comment that added more context to the problem and makes me think otherwise, but your desired end result is still unclear.
Upvotes: 2