Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a String to Java Code at Runtime

I have a filtering application written in Java that will allow me to filter companies based on their fundamentals (e.g. pretax profit, dividend yield etc.).

I have created a filtering engine that, at the moment is hard-coded to take filters that have been given at compile time.

What I want to do is open up a web service where I can pass in JSON to run the filtering using filters defined and passed in at runtime.

To do this I need to somehow convert strings into Java code.

So for example the following string in JSON:

current.preTaxProfit > previous.preTaxProfit

into Java code like this:

return current.getPreTaxProfit() > previous.getPreTaxProfit();

The main issue I am having is parsing mathematical strings such as:

current.preTaxProfit > (previous.preTaxProfit * 1.10)

Things could get very complex very quickly, especially when it comes to inner brackets and such, and adhering to BODMAS.

Are there any libraries out there specifically for parsing mathematical strings, or does anyone know any good resources that could help me?

For example, I have found this:

Javaassist: http://davidwinterfeldt.blogspot.co.uk/2009/02/genearting-bytecode.html

Does anyone have any experience of using Javaassist? In my architecture I pass in objects ith 'callback' methods implemented, so the ability to create entire classes and methods could useful.

like image 798
Armada Avatar asked Aug 28 '26 07:08

Armada


1 Answers

Two possibilities:

  • the Java Scripting API:
  • the EL, Expression Language.

The scripting API might be most fast to get results from, but EL is nicer.

like image 121
Joop Eggen Avatar answered Aug 29 '26 22:08

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!