Search code examples
javaspringruntimebeanshellgroovyshell

How to call Java method that stored in string variable


first, this is not similar to other questions because expressions contains parameters.

assume we have this method:

 public static int test(int x, Double y) {
    return somthing
}

and we have string expression like this:

 String expression = "test(1, 2)";

so how can we run this expression ?

I want to write a method with parameter and call it from a expression .

I can't find any library to solve this problem.

please help


Solution

  • You can use the Script Engine with a scripting language, such as JavaScript, to handle your expressions.

    package expression;
    
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    public class App 
    {
        public static void main( String[] args )
        {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("nashorn");
            try {
                engine.eval("var test = Packages.expression.App.test");
                Object result = engine.eval("test(1,2)");
                System.out.println(result);
            } catch (ScriptException e) {
                //TODO: handle exception
                e.printStackTrace();
            }
        }
    
        public static int test(int x, Double y) {
            return x;
        }
    }
    

    The line "var test = Packages.expression.App.test" creates an alias to your method.

    The line Object result = engine.eval("test(1,2)"); calls your method.

    You need to include the following dependency to your maven pom.xml:

    <dependency>
      <groupId>org.openjdk.nashorn</groupId>
      <artifactId>nashorn-core</artifactId>
      <version>15.1</version>
    </dependency>