Armada
Armada

Reputation: 728

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.

Upvotes: 3

Views: 849

Answers (2)

Artur Malinowski
Artur Malinowski

Reputation: 1144

Consider using of an expression language, for instance JEXL.

If you put current and previous into the context, just evaluate:

current.preTaxProfit > (previous.preTaxProfit * 1.10)

Complete example:

// create context
JexlContext jc = new MapContext();
context.set("current", someObject);
context.set("previous", anotherObject);

// create expression
String jexlExp = "current.preTaxProfit > (previous.preTaxProfit * 1.10)";
Expression e = jexl.createExpression(jexlExp);

// evaluate
Object result = e.evaluate(jc);

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

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.

Upvotes: 2

Related Questions