Can I strictly evaluate a boolean expression stored as a string in Java?

Posted by D Lawson on Stack Overflow See other posts from Stack Overflow or by D Lawson
Published on 2010-06-07T18:26:27Z Indexed on 2010/06/07 18:32 UTC
Read the original article Hit count: 191

Filed under:
|
|
|

I would like to be able to evaluate an boolean expression stored as a string, like the following:

"hello" == "goodbye" && 100 < 101

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, BeanShell, and it allows for the evaluation of statements like this one

"hello" == 100

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).

Here's the code that I'm using currently:

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");
}

© Stack Overflow or respective owner

Related posts about java

Related posts about boolean