0

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

10
  • you can write your own Commented May 20, 2021 at 13:32
  • Do you know what input you are going to have? For example if you are creating a calculator you can enter some expressions like: sum, divide, minus which are limited number and you know them all. Or your use case should cover any kind of method name given in the expression? Commented May 20, 2021 at 13:40
  • Your basically talking about writing a parser here. stackoverflow.com/questions/34432136/… Commented May 20, 2021 at 13:42
  • @Aethernite I know that. I edit the question. I want to write a method with parameter and call it as a expression Commented May 20, 2021 at 13:45
  • @Stultuske can you tell me how? Commented May 20, 2021 at 13:47

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.