2

我正在弄清楚 Java 的脚本支持,我目前有这个测试类

import java.io.FileNotFoundException;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;



/**
 *
 * @author Makerimages
*/
public class main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws ScriptException, FileNotFoundException, NoSuchMethodException {

    // create a script engine manager
    ScriptEngineManager factory = new ScriptEngineManager();
    // create JavaScript engine
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    // evaluate JavaScript code from given file - specified by first argument
    engine.eval(new java.io.FileReader("C:/Users/**/Documents/NetBeansProjects/test/src/l.js"));

}
public void makeObject(String s)
{
    System.out.println(s);
}

}

和这个 l.js 文件

makeObject("afzsdf");

当我尝试运行它时,我得到

运行:线程“main”中的异常 javax.script.ScriptException:sun.org.mozilla.javascript.internal.EcmaError:ReferenceError:“makeObject”未定义。(#1) 在第 1 行的 com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:224) 在 javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:249) 在 main.main(main. java:34) 原因:sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "makeObject" is not defined。(#1) sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3771) sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3749) sun.org .mozilla.javascript.internal.ScriptRuntime.notFoundError(ScriptRuntime.java:3834) 在 sun.org.mozilla.javascript。

我该如何修复它,以便我可以在脚本中使用 makeObject 函数???

4

1 回答 1

0

您需要添加绑定,例如将您的 Java 对象链接到 JS 范围。

爪哇:

import javax.script.*;
import java.io.FileNotFoundException;

public class main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ScriptException, FileNotFoundException, NoSuchMethodException {

        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");

        //bind main instance
        Bindings bindings = engine.createBindings();
        bindings.put("main", new main());
        engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);

        // evaluate JavaScript code from given file - specified by first argument
        engine.eval(new java.io.FileReader("l.js"));

    }

    public void makeObject(String s) {
        System.out.println(s);
    }
}

在 JS 中你引用这个main对象:

main.makeObject("afzsdf");
于 2013-10-27T21:18:43.083 回答