问题
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) {
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(List<String> listOfStrings){
System.out.println("I am inside method 1");
}
}
Now as you can see in the expression, to call method1, I need to pass a list as arguments. How to do that? What changes are required in the expression? What if I want to pass dynamic arguments in my program?
回答1:
You can create a List
or have it coming from some other source as an argument.
Only thing you need to take care is to put inside the
map
object, which used byMVEL
for evaluation.
Need to pass list as mentioned -> obj.method1(myList);
Working Code Below
public class SomeClass {
public static void main(String[] args) {
SomeClass myObj = new SomeClass();
Map<String, Object> map = new HashMap<String, Object>();
map.put("obj", myObj);
List<String> listOfStrings = new ArrayList<String>();
listOfStrings.add("my ");
listOfStrings.add("List ");
listOfStrings.add("is printing");
map.put("obj", myObj);
map.put("myList", listOfStrings);
MVEL.eval("System.out.println(\"I am inside main method\");obj.method1(myList);",map);
}
public static void method1(List<String> listOfStrings) {
System.out.println("I am inside method 1");
for (String s : listOfStrings) {
System.out.print(s);
}
}
}
output
I am inside main method
I am inside method 1
my List is printing
来源:https://stackoverflow.com/questions/34150207/how-to-pass-arguments-to-a-function-written-inside-an-mvel-expression