How to pass arguments to a function written inside an MVEL expression?

一笑奈何 提交于 2020-01-04 02:26:28

问题


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 by MVEL 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!