在Java中使用JavaScript脚本的方法步骤大致如下:
- 导入JavaScript引擎
- Java 8及以后版本使用Nashorn引擎(已废弃):
```java
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
- Java 11及以后版本使用GraalVM引擎:
java
import org.graalvm.polyglot.Context;
Context graalVMContext = Context.newBuilder("js").build();
```
-
载入JavaScript脚本文件或直接执行脚本字符串
-
从文件载入脚本:
```java
import java.io.FileReader;
FileReader reader = new FileReader("path/to/script.js");
engine.eval(reader);
```
- 直接执行脚本字符串:
java
String script = "function square(number) { return number * number; }";
engine.eval(script);
-
调用JavaScript函数和获取脚本返回值
-
调用JavaScript函数:
```java
// 假设在脚本中定义了一个名为add的函数
String script = "function add(a, b) { return a + b; }";
engine.eval(script);
// 调用这个函数
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("add", 1, 2);
// 此时result的值为3
```
- 获取脚本返回值:
java
String script = "var x = 2 * 3; x;";
Object result = engine.eval(script);
// 此时result的值为6
示例1:从文件载入脚本并调用JavaScript函数
import javax.script.*;
import java.io.*;
public class Example1 {
public static void main(String[] args) throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
FileReader reader = new FileReader("path/to/script.js");
engine.eval(reader);
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("myFunction", "John");
System.out.println(result);
}
}
示例2:直接执行脚本字符串并获取脚本返回值
import javax.script.*;
public class Example2 {
public static void main(String[] args) throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
String script = "var x = 2 * 3; x;";
Object result = engine.eval(script);
System.out.println(result);
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java中使用JavaScript脚本的方法步骤 - Python技术站