We want to execute the execute(s1,s2) method in JavaScriptMethods.js. The content of the JavaScriptMethods.js file is as follows:
function execute(s1, s2){ return s1 + s2;}First, you need to define an interface, which gives the same method signature as the JavaScript method to be executed. We define the interface Methods, and its content is as follows:
/** * The method signature in the interface must be consistent with the JavaScript method to be executed* @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. The specific content is written in the following ExecuteScript class:
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); // The parameter of FileReader is the path of the js file to be executed 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 the ExecuteScript class and the output is as follows:
/C:/Users/yuncong/git/login/target/classes/executescript/ liyuncong
The above is all about this article, I hope it will be helpful to everyone's learning.