I want to convert some String to an operator like this:
int value = 1;
int valueToCompare = 3;
String operation = \"<\";
if (value operation
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);
}