All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.houbb.value.extraction.test.js.JavaScriptExample Maven / Gradle / Ivy

There is a newer version: 0.8.0
Show newest version
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();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy