Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mvel

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?

like image 327
Anuj Avatar asked Jan 08 '23 01:01

Anuj


2 Answers

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
like image 147
Ankur Singhal Avatar answered Mar 15 '23 23:03

Ankur Singhal


There are two ways to call your own method in MVEL. First way like @Ankur Singhal's answer. And another way is use ParserContext.

Here is the Class

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

Use ParserContext to import the Class to MVEL.

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

Then you can call static method of the Class in your expression.

Serializable s = MVEL.compileExpression("CalcHelper.add(1,2)", parserContext);
MVEL.executeExpression(s, parserContext);
like image 28
Dre Avatar answered Mar 16 '23 00:03

Dre