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

前提是你 提交于 2019-12-04 11:14:48

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.

Try the eval project

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

Its like eval for java

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()".

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

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