I want to convert some String
to an operator like this:
int value = 1;
int valueToCompare = 3;
String operation = \"<\";
if (value operation
The simplest way would be a chain of if-else statements checking what the the operator is and then performing the mathematical expression.
Your approach will never work in Java. Instead you may define your own enum
which perform the proper boolean operation like this:
public static void main(String[] args) {
boolean result = Operator.parseOperator("==").apply(2, 2);
}
enum Operator {
LESS("<") {
@Override public boolean apply(int left, int right) {
return left < right;
}
},
EQUAL("==") {
@Override public boolean apply(int left, int right) {
return left == right;
}
};
private final String operator;
private Operator(String operator) {
this.operator = operator;
}
public static Operator parseOperator(String operator) {
for (Operator op : values()) {
if (op.operator.equals(operator)) return op;
}
throw new NoSuchElementException(String.format("Unknown operator [%s]", operator));
}
public abstract boolean apply(int left, int right);
}
You can use ScriptEngine for that, works for any other JavaScript expressions also :
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
int value = 1;
int valueToCompare = 3;
String operation = "<";
if ((Boolean)engine.eval("" + value + operation + valueToCompare)) {
System.out.println("Here we are.");
}