如何从 MVEL 表达式中调用外部方法?

How to call an external method from within an MVEL expression?

我有一个 JAVA class 有两种方法。第一个是main方法,第二个是method1()。

假设以下是 class:

public class SomeClass() {
  public static void main(String[] args){
    MVEL.eval("System.out.println(\"I am inside main method\");method1();");
  }
  public static void method1(){
    System.out.println("I am inside method 1");
  }
}

现在当我 运行 程序时,我得到以下输出:-

我在main方法里面

Exception in thread "main" [Error: no such method or function: method1]
[Near : ... main method"); method1(); ..}]
                                    ^
[Line: 1, Column: 184]
at org.mvel2.PropertyAccessor.getMethod(PropertyAccessor.java:898)
at org.mvel2.PropertyAccessor.getNormal(PropertyAccessor.java:182)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:146)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:126)
at org.mvel2.ast.ASTNode.getReducedValue(ASTNode.java:187)
at org.mvel2.MVELInterpretedRuntime.parseAndExecuteInterpreted(MVELInterpretedRuntime.java:106)
at org.mvel2.MVELInterpretedRuntime.parse(MVELInterpretedRuntime.java:49)
at org.mvel2.MVEL.eval(MVEL.java:136)
at mypackage.SomeClass.main(SomeClass.java:15)

如您所见,它打印了第一个 sop,但是当调用 method1 时,它抛出异常。

有办法解决这个问题吗?

通过MVEL求值时需要传递class对象。

1.) SomeClass 已创建

2.) map.put("obj", myObj); 添加到 HashMap

3.) MVEL.eval(exp,map)需要评估

public static void main(String[] args) {
        SomeClass myObj = new SomeClass();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("obj", myObj);
        MVEL.eval("System.out.println(\"I am inside main method\");obj.method1();",map);
    }

    public static void method1() {
        System.out.println("I am inside method 1");
    }

输出

I am inside main method
I am inside method 1

在MVEL中调用自己的方法有两种方式。第一种方式就像@Ankur Singhal 的回答。另一种方法是使用 ParserContext。

这是Class

public class CalcHelper {
    public static int add(int a, int b){
        return a + b;
    }
}

使用 ParserContext 将 Class 导入 MVEL。

ParserContext parserContext = new ParserContext();
parserContext.addImport(CalcHelper.class.getSimpleName(), CalcHelper.class);

然后你可以在你的表达式中调用Class的静态方法。

Serializable s = MVEL.compileExpression("CalcHelper.add(1,2)", parserContext);
MVEL.executeExpression(s, parserContext);