条件字符串解析器在Java API中?

时间:2013-12-27 07:55:22

标签: java

我想解决以下条件字符串。因为我想在我的项目中支持动态条件。

a != 0 && b > 5

我的预期计划是

public boolean resolve() {
    String condition = "a != 0 && b > 5";
    Map<String, Object> paramMap = new HashMap<String, Object>;
    paramMap.put("a", 2);
    paramMap.put("b", 6);
    boolean result = ConditionResolver.resolve(condition, paramMap);
    if(result) {
        //do something
    }
} 

更新:

我不是要解决数学等式,如下所示

((a + b) * y) /x

2 个答案:

答案 0 :(得分:6)

从java 1.6开始,您可以使用ScriptEngine并评估 javascript ,如果这对您来说足够和/或您不想引入其他库。

ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("javascript");
SimpleBindings bindings = new SimpleBindings();

bindings.put("a", 0);
bindings.put("b", 6);

boolean firstEval =  (Boolean) scriptEngine.eval("a != 0 && b > 5", bindings);
System.out.println(firstEval);

bindings.put("a", 2);
bindings.put("b", 6);

boolean secondEval =  (Boolean) scriptEngine.eval("a != 0 && b > 5", bindings);
System.out.println(secondEval);

输出

false
true

答案 1 :(得分:1)

我认为你应该使用表达式库。可能这篇文章会帮助你Built-in method for evaluating math expressions in Java

对于评估逻辑表达式,请参阅以下库:JANINO

实施例

import java.lang.reflect.InvocationTargetException;

import org.codehaus.commons.compiler.CompileException;
import org.codehaus.janino.ExpressionEvaluator;

public class WorkSheet_1{
    public static void main(String[] args) throws CompileException, InvocationTargetException {
        ExpressionEvaluator ee = new ExpressionEvaluator(
                "a != 0 && b > 5",                     
                boolean.class,                           
                new String[] { "a", "b" },           
                new Class[] { int.class, int.class } 
            );

        Boolean res1 = (Boolean) ee.evaluate(new Object[] {new Integer(2), new Integer(6),});
        System.out.println("res1 = " + res1);
        Boolean res2 = (Boolean) ee.evaluate(new Object[] {new Integer(2), new Integer(5),});
        System.out.println("res2 = " + res2);
    }
}

<强>输出

res1 = true
res2 = false