Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I strictly evaluate a boolean expression stored as a string in Java?
    text
    copied!<p>I would like to be able to evaluate an boolean expression stored as a string, like the following:</p> <pre><code>"hello" == "goodbye" &amp;&amp; 100 &lt; 101 </code></pre> <p>I know that there are tons of questions like this on SO already, but I'm asking this one because I've tried the most common answer to this question, <a href="http://www.beanshell.org/" rel="nofollow noreferrer">BeanShell</a>, and it allows for the evaluation of statements like this one</p> <pre><code>"hello" == 100 </code></pre> <p>with no trouble at all. Does anyone know of a FOSS parser that throws errors for things like operand mismatch? Or is there a setting in BeanShell that will help me out? I've already tried Interpreter.setStrictJava(true).</p> <p>For completeness sake, here's the code that I'm using currently:</p> <pre><code>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"); } </code></pre> <p><strong>Edit:</strong></p> <p>The code I have currently returns this output</p> <pre><code>result: false </code></pre> <p>without error. What I would like it to do is throw an EvalError or <em>something</em> letting me know that there were mismatched operands.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload