[英]MVEL to validate arithmetic expression without values
我想在不提供輸入或值的情況下驗證給定的算術表達式(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: )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.