如何在 MVEL 表达式中使用变量?

我的 Java 代码中有预定义的变量,我想在 MVEL 表达式中使用它们。我不想传递上下文。


String Col1 = "C";

String Col2 = "D";

String expression = "Col1 == 'C' && Col2 == 'D'";


Boolean result = (Boolean) MVEL.eval(expression);

如何读取变量值并将表达式计算为 true 或 false?


白板的微信
浏览 56回答 1
1回答

喵喵时光机

您需要将变量添加col1到col2上下文对象中,然后将该对象传递给MVEL.eval. 下面给出的是工作示例:import java.util.HashMap;import java.util.Map;import org.mvel2.MVEL;public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> context = new HashMap<String, Object>();&nbsp; &nbsp; &nbsp; &nbsp; String col1 = "C";&nbsp; &nbsp; &nbsp; &nbsp; String col2 = "D";&nbsp; &nbsp; &nbsp; &nbsp; context.put("col1", col1);&nbsp; &nbsp; &nbsp; &nbsp; context.put("col2", col2);&nbsp; &nbsp; &nbsp; &nbsp; String expression = "col1 == 'C' && col2 == 'D'";&nbsp; &nbsp; &nbsp; &nbsp; Boolean result = (Boolean) MVEL.eval(expression,context);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(result);//true&nbsp; &nbsp; &nbsp; &nbsp; expression = "col1 == 'E' && col2 == 'D'";&nbsp; &nbsp; &nbsp; &nbsp; result = (Boolean) MVEL.eval(expression,context);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(result);//false&nbsp; &nbsp; }}如果您还有任何疑问,请随时告诉我。更新:以下更新是解释为什么您需要上下文对象(您在评论中提到您不想将变量添加到上下文对象)。如果您查看https://github.com/mvel/mvel/blob/master/src/main/java/org/mvel2/MVEL.java上的文档,您会很想使用以下方法:public static Object eval(String expression) {&nbsp; &nbsp; return new MVELInterpretedRuntime(expression, new ImmutableDefaultFactory()).parse();}但是,下面的代码将无法编译:String col1 = "C";String col2 = "D";String expression = "col1 == 'C' && col2 == 'D'";System.out.println(new MVELInterpretedRuntime(expression, new ImmutableDefaultFactory()).parse());原因是,以下构造函数的可见性不是public。MVELInterpretedRuntime(String expression, VariableResolverFactory resolverFactory) {&nbsp; &nbsp; setExpression(expression);&nbsp; &nbsp; this.variableFactory = resolverFactory;}因此,您需要在客户端程序中填充一个上下文对象,并将该对象与表达式一起传递给评估 MVEL 表达式的程序/方法。在我的程序中,这是main我填充上下文对象以及评估 MVEL 表达式的方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java