欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java:ScriptEngine执行js代码

程序员文章站 2022-06-07 13:22:53
...

JDK >= 6

package com.demo.desktop;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaScriptDemo {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("javascript");
        String script = "print('Hello')";

        // 执行脚本
        engine.eval(script);
    }
}