简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM