在Java中調(diào)用JS腳本的方法通常使用ScriptEngine類,該類是Java中用來執(zhí)行腳本的API。具體步驟如下:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String script = "function greet(name) { return 'Hello, ' + name; }";
engine.eval(script);
Invocable inv = (Invocable) engine;
String result = (String) inv.invokeFunction("greet", "World");
System.out.println(result); // 輸出:Hello, World
通過這種方法,可以在Java中調(diào)用JS腳本中定義的函數(shù)或方法,并獲取返回值。