Java executes JavaScript code

  • 2020-05-07 19:42:01
  • OfStack

We will execute the execute(s1,s2) method in JavaScriptMethods.js in Java, JavaScriptMethods.js file as follows:


function execute(s1, s2){
  return s1 + s2;
}

First of all, we need to define an interface, which gives the method signature similar to the JavaScript method 1 to be executed. We define the interface Methods, which is as follows:


/**
 *  The method signature in the interface must correspond to the one to be executed JavaScript methods 1 to 
 * @author yuncong
 *
 */
public interface Methods {
  public String execute(String s1,String s2);
}

Then, you can use the script engine to execute the execute(s1,s2) method in JavaScriptMethods.js, which is written in the ExecuteScript class below:


import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;


public class ExecuteScript {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    try {
      String path = ExecuteScript.class.getResource("").getPath();
      System.out.println(path);
      // FileReader Is the parameter to be executed js Path to file 
      engine.eval(new FileReader(path + "JavaScriptMethods.js"));
      if (engine instanceof Invocable) {
        Invocable invocable = (Invocable) engine;
        Methods executeMethod = invocable.getInterface(Methods.class);
        System.out.println(executeMethod.execute("li", "yuncong"));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Run ExecuteScript class and the output is as follows:


/C:/Users/yuncong/git/login/target/classes/executescript/ 
liyuncong

The above is the entire content of this article, I hope to help you with your study.


Related articles: