如何解决MVEL 验证没有值的算术表达式
我想在不提供输入或值的情况下验证给定的算术表达式 (a+b)
是否有效。
我尝试使用 ExpressionCompiler
和 MVEL.compileExpression()
如下,
String expression = "a+b";
ExpressionCompiler c = new ExpressionCompiler(formula,ctx );
//c.setVerifyOnly(true); // tried this but didn't help
c.compile() // this will throw exception if expression is invalid
这适用于大多数情况,例如 a+b*
,但是当表达式为 a+b)
时,这被编译为有效表达式,编译器不会抱怨额外的括号。
有什么办法可以让MVEL来验证这种a+b)类的表达式吗?
解决方法
终于找到了如何在不提供值或输入的情况下验证表达式。
解决方法很简单,只需要启用ParserContext.setStrictTypeEnforcement(true)
下面是代码,
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true); // this made the trick
ExpressionCompiler c = new ExpressionCompiler(formula,ctx );
c.compile();// now this throws exception for a+b) -> unqualified type in strict mode for: )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。