I'm looking for a relatively simpler (when compared with writing a parser) way to evaluate boolean expressions in Java, and I do not want to use the JEP library.
I have a String expression like: (x > 4 || x < 8 && p > 6)
and my aim is to replace the variables with values.
Is there a way by which I can evaluate this expression?
Bear in mind that this can be any level deep so writing a parser would be very complex.
These operators include equality ( == ) and inequality ( != ). The former operator returns true when both operands are equal; the latter operator returns true when both operands are unequal.
A Boolean expression is a Java expression that returns a Boolean value: true or false .
Use Apache Commons Jexl; which is exactly designed for such requirement.
http://commons.apache.org/jexl/
Using jexl (http://commons.apache.org/jexl/), you can accomplish this like this
JexlEngine jexl = new JexlEngine();
jexl.setSilent(true);
jexl.setLenient(true);
Expression expression = jexl.createExpression("(a || b && (c && d))");
JexlContext jexlContext = new MapContext();
//b and c and d should pass
jexlContext.set("b",true);
jexlContext.set("c",true);
jexlContext.set("d",true);
assertTrue((Boolean)expression.evaluate(jexlContext));
jexlContext = new MapContext();
//b and c and NOT d should be false
jexlContext.set("b",true);
jexlContext.set("c",true);
//note this works without setting d to false on the context
//because null evaluates to false
assertFalse((Boolean)expression.evaluate(jexlContext));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With