通过Java执行的JavaScript调用Java方法

■ 第一个链接是本家文件(1),它位于https://docs.oracle.com/javase/jp/6/technotes/guides/scripting/programmer_guide/。
■ 第二个链接是本家文件(2),它位于https://developer.mozilla.org/ja/docs/Rhino/Scripting_Java。


package pkg;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class HelloJavaScript {
    public void run() {
        System.err.println("hello!");
    }
    public static void main(String[] args) {
        // see
        // https://developer.mozilla.org/ja/docs/Rhino/Scripting_Java
        // These packages are likely not in the java package, so you'll need to
        // prefix the package name with "Packages."

        // Get the JavaScript engine
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        String script = "" //
                + "var obj = new Packages.pkg.HelloJavaScript();" //
                + "obj.run();" //
        ;
        try {
            engine.eval(script);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}
广告
将在 10 秒后关闭
bannerAds