Can I strictly evaluate a boolean expression stored as a string in Java?

不想你离开。 提交于 2019-12-06 05:16:37

问题


I would like to be able to evaluate an boolean expression stored as a string, like the following:

"hello" == "goodbye" && 100 < 101

I know that there are tons of questions like this on SO already, but I'm asking this one because I've tried the most common answer to this question, BeanShell, and it allows for the evaluation of statements like this one

"hello" == 100

with no trouble at all. Does anyone know of a FOSS parser that throws errors for things like operand mismatch? Or is there a setting in BeanShell that will help me out? I've already tried Interpreter.setStrictJava(true).

For completeness sake, here's the code that I'm using currently:

Interpreter interpreter = new Interpreter();
interpreter.setStrictJava(true);    
String testableCondition = "100 == \"hello\"";
try {
    interpreter.eval("boolean result = ("+ testableCondition + ")");
    System.out.println("result: "+interpreter.get("result"));
    if(interpreter.get("result") == null){
        throw new ValidationFailure("Result was null");
    }
} catch (EvalError e) {
    e.printStackTrace();
    throw new ValidationFailure("Eval error while parsing the condition");
}

Edit:

The code I have currently returns this output

result: false

without error. What I would like it to do is throw an EvalError or something letting me know that there were mismatched operands.


回答1:


In Java 6, you can dynamically invoke the compiler, as explained in this article:

http://www.ibm.com/developerworks/java/library/j-jcomp/index.html

You could use this to dynamically compile your expression into a Java class, which will throw type errors if you try to compare a string to a number.




回答2:


Try the eval project




回答3:


Use Janino! http://docs.codehaus.org/display/JANINO/Home

Its like eval for java




回答4:


MVEL would also be useful

http://mvel.codehaus.org/

one line of code to do the evaluation in most cases:

Object result = MVEL.eval(expression, rootObj);

"rootObj" could be null, but if it's supplied you can refer to properties and methods on it without qualificiation. ie. "id" or "calculateSomething()".




回答5:


You can try with http://groovy.codehaus.org/api/groovy/util/Eval.html if groovy is an option.



来源:https://stackoverflow.com/questions/2992071/can-i-strictly-evaluate-a-boolean-expression-stored-as-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!