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?
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With