简体   繁体   English

在Java中验证MVEL表达式

[英]Validate MVEL expression in java

User will enter some formula/expression. 用户将输入一些公式/表达式。

I want to check whether the formula/expression which is a String input to my function is correct(as per MVEL standard) or not. 我想检查作为函数输入的String的公式/表达式是否正确(按照MVEL标准)。

Following is a valid expression, 以下是有效的表达式,

String validFormula = "if(dueDate > "2015-12-12") {a*b} else {a+b}";

Following is incorrect expression, 以下是错误的表达,

String invalidFormula = "if(dueDate > 2015-12-12) {a*b} else {a+b}";
 //Quotes are missing for date

Following is code snippet, 以下是代码段,

public Formula save(String formula)
{
    // want to call MVEL api to check if formula/expression is valid or not
    ...
}

Is there any api provided by MVEL which accepts expression String and return boolean/throw exception if expression is incorrect? MVEL是否提供任何api来接受表达式String并在表达式不正确时返回布尔值/抛出异常?

you can validate the expression using 您可以使用以下方式验证表达式

Serializable compiledFormula = MVEL.compileExpression(validFormula);
Serializable compiledFormula = MVEL.compileExpression(invalidFormula);

This results in org.mvel2.CompileException if invalid. 如果无效,这将导致org.mvel2.CompileException

This works with mvel 2.2.6, cannot guarantee the API compatibility or the functionality with older versions of library. 这适用于mvel 2.2.6,不能保证API兼容性或旧版本库的功能。

Also please note, in your case both expressions will be valid since MVEL does not know the data type of duedate variable, which will be known only at the run time, when you actually execute the expression. 还请注意,在您的情况下,这两个表达式都是有效的,因为MVEL不知道duedate变量的数据类型,只有实际运行表达式时,才在运行时才知道。 Hope this helps... 希望这可以帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM