简体   繁体   中英

Java: Library for expression parsing & evaluation with identifiers not known in advance

I need to evaluate a boolean expression. The purpose is to filter a set of tagged items . Tag can be any name (let's say, like Java identifier).

For example:

foo OR (bar AND !baz)

This would be true for items tagged:

  • foo fee
  • foo bar boo
  • bar

I don't know in advance which names will be needed. I've checked JEXL but it has JexlContext , which is basically a Map which needs to be filled prior to evaluation.

I need some library which calls a callback function to decide whether an identifier is true or false. Or any other mechanism to allow identifiers unknown prior to evaluation.

It has to be free as in beer (it's for a Maven plugin), so Jep is out of question.

What can I use?

You can provide an implementation of JexlContext that does not rely on a Map . Instead of filling it before evaluation, you can treat its checks for has , get as your callbacks, and ignore the calls to set .

在Google的番石榴中尝试谓词

The easiest way is to use JavaScript that is a part of JDK since java 6. Here is an example

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    // populate variables foo, bar and baz to the engine, e.g.
    engine.put("foo", true);
    engine.put("bar", true);
    engine.put("baz", false);
    engine.eval("foo OR (bar AND !baz)"); 

For more information take a look on the tutorial from Oracle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM