简体   繁体   English

Java:用于使用未知标识符进行表达式解析和评估的库

[英]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). 标记可以是任何名称(例如Java标识符)。

For example: 例如:

foo OR (bar AND !baz)

This would be true for items tagged: 对于标记为:

  • foo fee foo费用
  • foo bar boo 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. 我已经检查了JEXL,但是它具有JexlContext ,它基本上是一个Map,需要在评估之前进行填充。

I need some library which calls a callback function to decide whether an identifier is true or false. 我需要一些库,该库调用回调函数来确定标识符是true还是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. 它必须像啤酒一样免费(用于Maven插件),因此Jep毫无疑问。

What can I use? 我可以使用什么?

You can provide an implementation of JexlContext that does not rely on a Map . 您可以提供不依赖于MapJexlContext实现。 Instead of filling it before evaluation, you can treat its checks for has , get as your callbacks, and ignore the calls to set . 无需在评估之前填充它,您可以对待它的has进行检查, get为您的回调并忽略set的调用。

在Google的番石榴中尝试谓词

The easiest way is to use JavaScript that is a part of JDK since java 6. Here is an example 最简单的方法是使用自Java 6以来属于JDK的JavaScript。这是一个示例

    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 . 有关更多信息,请查看Oracle的教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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