We want to execute the Execute (S1,S2) method in Javascriptmethods.js in Java, javascriptmethods.js the contents of the file are as follows:
function execute (S1, S2) {return
s1 + s2;
}
First you need to define an interface that gives the same method signature as the JavaScript method to be executed, and we define the interface methods, which reads 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);
You can then use the scripting engine to execute the Javascriptmethods.js execute (s1,s2) method, which 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 Scriptengi Nemanager ();
ScriptEngine engine = Manager.getenginebyname ("JS");
try {
String path = ExecuteScript.class.getResource (""). GetPath ();
SYSTEM.OUT.PRINTLN (path);
The FileReader parameter 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, 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 learn.