Search code examples
mvel

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


I have a JAVA class that has two methods. The first one is the main method and the second one is method1().

Let's say the following is the 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");
  }
}

Now when I run the program, I get the following output:-

I am inside main method

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)

As you can see, it prints the first sop, but when it comes to calling method1, it throws exception.

Is there a way to fix this issue?


Solution

  • You need to pass the class object while evaluating through MVEL.

    1.) SomeClass is created

    2.) map.put("obj", myObj); added to HashMap

    3.) MVEL.eval(exp,map) need to evaluate

    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");
        }
    

    output

    I am inside main method
    I am inside method 1