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

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.

+4
source share
5 answers

In Java 6, you can dynamically invoke the compiler, as described in this article:

http://www.ibm.com/developerworks/java/library/j-jcomp/index.html

You can use this to dynamically compile your expression into a Java class that will cause type errors if you try to compare a string with a number.

+2
source
0
source

Use Yanino! http://docs.codehaus.org/display/JANINO/Home

This is similar to eval for java

0
source

MVEL will also be useful

http://mvel.codehaus.org/

one line of code to evaluate in most cases:

 Object result = MVEL.eval(expression, rootObj); 

"rootObj" may be null, but if provided, you can refer to the properties and methods on it without qualification. i.e. "id" or "calculateSomething ()".

0
source

You can try http://groovy.codehaus.org/api/groovy/util/Eval.html if the option is groovy.

0
source

Source: https://habr.com/ru/post/1312123/


All Articles