Boolean Expression Evaluation in Java

前端 未结 10 1326
-上瘾入骨i
-上瘾入骨i 2020-12-05 16:26

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.

I

10条回答
  •  春和景丽
    2020-12-05 16:47

    Using jexl (http://commons.apache.org/jexl/), you can accomplish this like this

        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));
    

提交回复
热议问题