views:

534

answers:

6

Hey everyone, Is there a relatively simpler (when compared with writing a parser) way to evaluate boolean expressions in Java? I do not want to use the JEP library. I have a String expression something like: (x > 4 || x < 8 && p > 6) [ I will replace the variables with values. Is there a way by which I can evaluate this expression?

The problem is, this can be any level deep. So, writing a parser would be really complex.

Thanks

A: 

JUEL provides an implementation of Java's Unified Expression Language without being explicitly tied to JSP. Here's its Quick Start guide, expression evaluation (#3 on that page) is the part you're interested in.

Alternatively, Spring 3.0 provides its own (though somewhat similar) expression language. This option only makes sense if you're already using Spring, though - I wouldn't pull it in just for EL.

ChssPly76
+2  A: 

Use Apache Commons Jexl; which is exactly designed for such requirement.

http://commons.apache.org/jexl/

Venkat
+1 Here's a good example of how it's used. http://commons.apache.org/jexl/reference/examples.html
blak3r
+2  A: 

You could use the scripting engine in Java6 and the choose any number of popular languages like Scala, Ruby, Python, Groovy, and Javascript. The all you have to do is make sure the expression you want to eval is in the right language. Groovy is probably the easiest and best integration.

I have used this successfully for a feature much like a formula/calculated column in a popular spreadsheet application

basszero
A: 

There is a API available at http://lts.online.fr/dev/java/math.evaluator/

Example: MathEvaluator m = new MathEvaluator("-5-6/(-2) + sqr(15+x)"); m.addVariable("x", 15.1d); System.out.println( m.getValue() );

Azeem
A: 

Try http://code.google.com/p/xpressionengine/ for open source implementation

Mohit
A: 

Here is the latest resources for expression evaluation framework

The information page is at http://expressionoasis.vedantatree.com/

Kaouni