user2869231
user2869231

Reputation: 1541

How to convert a String logical expression to java executable expression

This is unfortunately kind of ugly. I have a string written in a format that is sent as a constraint to a database. It looks something like this:

String constraint = "((attr1 eq 1) OR (attr2 eq 5)) AND (attr3 BETWEEN (1, 5))"

I need a way of parsing this into a stream filter, to look like so:

stream.filter(obj -> 
    (obj.getAttr1() == 1 || obj.getAttr2() == 5) && (isBetween(obj.getAttr3(), 1, 5)))

the isBetween method is elsewhere that would determine whether the attr3 value is between 1 and 5. Is there an easy way of parsing this?

It should be fine to have multiple filter calls rather than fitting it all into one. Deciding which getAttr to use can be done in an if statement along the lines of:

if (attr.equals("attr1")) {
    obj.getAttr1();
}

Upvotes: 1

Views: 152

Answers (1)

AJNeufeld
AJNeufeld

Reputation: 8705

You may wish to look into EvalEx. It is a general expression parser and evaluator.

You can define your own operators, so "eq", "and" and "or" shouldn't be a problem. You can create variables, so "attr1" and friends shouldn't be an issue either.

This one is likely the problem:

attr3 BETWEEN (1, 5)

Not sure if you can define an operator that take multiple arguments on the right side, or a function that returns a postfix operator. But the source code is available, so perhaps you can hack one in.

Upvotes: 1

Related Questions