I would like to be able to evaluate a boolean expression stored as a string, for example the following:
"hello" == "goodbye" && 100 < 101
I know there are a lot of such questions on SO already, but I ask about it because I tried the most general answer to this question, BeanShell , and this allows me to evaluate statements like this
"hello" == 100
no problem. Does anyone know of a FOSS parser that creates errors for things like operand mismatch? Or is there a setting in BeanShell that will help me? I already tried Interpreter.setStrictJava (true).
For completeness, here is the code I'm currently using:
Interpreter interpreter = new Interpreter(); interpreter.setStrictJava(true); String testableCondition = "100 == \"hello\""; try { interpreter.eval("boolean result = ("+ testableCondition + ")"); System.out.println("result: "+interpreter.get("result")); if(interpreter.get("result") == null){ throw new ValidationFailure("Result was null"); } } catch (EvalError e) { e.printStackTrace(); throw new ValidationFailure("Eval error while parsing the condition"); }
Edit:
The code I'm currently returning this output
result: false
no mistakes. I would like EvalError to do this or something letting me know that there were inconsistent operands.
source share