简体   繁体   English

Java 中的布尔表达式求值

[英]Boolean Expression Evaluation in Java

I'm looking for a relatively simpler (when compared with writing a parser) way to evaluate boolean expressions in Java, and I do not want to use the JEP library.我正在寻找一种相对更简单(与编写解析器相比)的方法来评估 Java 中的布尔表达式,并且我不想使用 JEP 库。

I have a String expression like: (x > 4 || x < 8 && p > 6) and my aim is to replace the variables with values.我有一个字符串表达式,如: (x > 4 || x < 8 && p > 6) ,我的目标是用值替换变量。

Is there a way by which I can evaluate this expression?有什么方法可以评估这个表达式吗?

Bear in mind that this can be any level deep so writing a parser would be very complex.请记住,这可以是任何深度,因此编写解析器将非常复杂。

Use Apache Commons Jexl;使用 Apache Commons Jexl; which is exactly designed for such requirement.这正是为这种要求而设计的。

http://commons.apache.org/jexl/ http://commons.apache.org/jexl/

Using jexl ( http://commons.apache.org/jexl/ ), you can accomplish this like this使用 jexl ( http://commons.apache.org/jexl/ ),你可以这样完成

    JexlEngine jexl = new JexlEngine();
    jexl.setSilent(true);
    jexl.setLenient(true);

    Expression expression = jexl.createExpression("(a || b && (c && d))");
    JexlContext jexlContext = new MapContext();

    //b and c and d should pass
    jexlContext.set("b",true);
    jexlContext.set("c",true);
    jexlContext.set("d",true);

    assertTrue((Boolean)expression.evaluate(jexlContext));

    jexlContext = new MapContext();

    //b and c and NOT d should be false
    jexlContext.set("b",true);
    jexlContext.set("c",true);

    //note this works without setting d to false on the context
    //because null evaluates to false

    assertFalse((Boolean)expression.evaluate(jexlContext));

You could use the scripting engine in Java6 and the choose any of the popular scripting languages like Scala , Ruby , Python , Groovy , and Javascript .您可以使用Java6 中的脚本引擎,并选择任何流行的脚本语言,如ScalaRubyPythonGroovyJavascript Than all you have to do is make sure the expression you want to evaluate is in the right language.您所要做的就是确保要评估的表达式使用正确的语言。 Groovy is probably the easiest and will integrate best. Groovy 可能是最简单的,并且集成度最高。

I have used this method successfully for a feature offering capabilities much like a formula / calculated column in a popular spreadsheet application.我已成功地将此方法用于提供功能的功能,该功能与流行的电子表格应用程序中的公式/计算列非常相似。

Here is the latest resources for expression evaluation framework这是表达式评估框架的最新资源

The information page is at http://expressionoasis.vedantatree.com/信息页面位于http://expressionoasis.vedantatree.com/

JUEL provides an implementation of Java's Unified Expression Language without being explicitly tied to JSP. JUEL提供了 Java 统一表达式语言的实现,而没有明确地绑定到 JSP。 Here's its Quick Start guide , expression evaluation (#3 on that page) is the part you're interested in.这是它的快速入门指南,表达式评估(该页面上的#3)是您感兴趣的部分。

Alternatively, Spring 3.0 provides its own (though somewhat similar) expression language.或者, Spring 3.0提供了自己的(虽然有些相似)表达式语言。 This option only makes sense if you're already using Spring, though - I wouldn't pull it in just for EL.不过,这个选项只有在您已经在使用 Spring 时才有意义 - 我不会只为 EL 使用它。

try Janino http://docs.codehaus.org/display/JANINO/Home It is very simple to use eg (taken from http://docs.codehaus.org/display/JANINO/Basic ):试试 Janino http://docs.codehaus.org/display/JANINO/Home使用起来非常简单,例如(取自http://docs.codehaus.org/display/JANINO/Basic ):

// Compile the expression once; relatively slow.
ExpressionEvaluator ee = new ExpressionEvaluator(
    "c > d ? c : d",                     // expression
    int.class,                           // expressionType
    new String[] { "c", "d" },           // parameterNames
    new Class[] { int.class, int.class } // parameterTypes
);

// Evaluate it with varying parameter values; very fast.
Integer res = (Integer) ee.evaluate(
    new Object[] {          // parameterValues
        new Integer(10),
        new Integer(11),
    }
);
System.out.println("res = " + res);

There is a API available at http://lts.online.fr/dev/java/math.evaluator/ http://lts.online.fr/dev/java/math.evaluator/提供了一个 API

Example:例子:

MathEvaluator m = new MathEvaluator("-5-6/(-2) + sqr(15+x)");
m.addVariable("x", 15.1d);
System.out.println( m.getValue() );

You could try this library https://github.com/Shy-Ta/expression-evaluator-demo - the read me has a fair number of examples.你可以试试这个库https://github.com/Shy-Ta/expression-evaluator-demo - read me 有很多例子。 The library uses java and groovy.该库使用 java 和 groovy。

In addition to supporting this use case, it also supports a lot of other excel like functions.除了支持这个用例之外,它还支持许多其他类似 excel 的功能。 Also, it is very simple to add new functions as demonstrated in the example.此外,添加新函数非常简单,如示例中所示。

      ExpressionsEvaluator evalExpr = ExpressionsFactory.create("(x > 4 || x < 8 && p > 6)");  
      Map<String, Object> variables = new HashMap<String, Object>();  
      variables.put("x", 100);  
      variables.put("p", 10);
      evalExpr.eval();

I found the libraries listed here too complicated for my needs.我发现这里列出的库对于我的需要来说太复杂了。 I ended up using Fscript: http://fscript.sourceforge.net/我最终使用了 Fscript: http ://fscript.sourceforge.net/

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

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