Tuesday, 5 November 2013

Dynamic Evaluation of expression in java

                                 Dynamically Evaluate expression in java

I am sure many people had already stumbled on this and recently I too became one of them . I was working on an assignment which needed some run time evaluation of expression. These expressions were not very complex of nature. They were pretty much like assign a variable with value 0 if that variable was null

something on the lines of :   abc=abc==null?0:abc

or something like  abc=abc=='D'?abc+'B':abc+'C'

now there was the way to build a kind of parser which parses these equations and provide the output , but every new requirement might need a enhancement to the parser.

Then going back to the basics I started googling around for solutions and stumbled across


This is basically a script engine (what the browsers internally might be using ) to do evaluation of javascript method like Eval.

And to my surprise it works pretty well . I understand there are pretty limitations to this engine ( as I read in of the blogs that it has issues with some regular expressions , not exactly sure which case was he mentioning ) , but it satisfies all the basic expressions.

This allowed me to store these expressions in some external properties files and invoke it dynamically and calculate the expressions.

May be worth trying if someone is looking for some utility under java.