Search code examples
javarulesmvel

MVEL to validate arithmetic expression without values


I want to verify if given arithmetic expression (a+b) is valid without providing inputs or values. I tried using ExpressionCompiler and MVEL.compileExpression() as below,

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

This works for most of the cases like a+b*, but when expression is a+b) this is compiled as valid expression, the compiler is not complaining the extra parenthesis.

Is there any way to make MVEL to verify this a+b) kind of expressions?


Solution

  • Finally found out how to validate expression without providing values or inputs. The solution is very simple, just need to enable ParserContext.setStrictTypeEnforcement(true)

    Below is the code,

    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: )