com.github.houbb.value.extraction.test.js.JavaScriptExample Maven / Gradle / Ivy
package com.github.houbb.value.extraction.test.js;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JavaScriptExample {
public static void main(String[] args) {
// 创建脚本引擎管理器
ScriptEngineManager manager = new ScriptEngineManager();
// 获取 JavaScript 引擎
ScriptEngine engine = manager.getEngineByName("nashorn");
// 创建绑定并设置参数
Bindings bindings = engine.createBindings();
bindings.put("name", "Alice");
bindings.put("age", 30);
// 定义 JavaScript 脚本
String script = "var greeting = 'Hello, ' + name + '! You are ' + age + ' years old.'; greeting;";
try {
// 执行脚本并传递参数
Object result = engine.eval(script, bindings);
System.out.println(result); // 输出结果
} catch (ScriptException e) {
e.printStackTrace();
}
}
}