开发者

Java Scripting Engine importing my classes does not work

A code is worth 1000 words of explaining it :-)

package jasim;

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

public class JSTest {

    public static void main(String[] args) throws ScriptException {
        ScriptEngine jse = new ScriptEngineManager().getEngineByExtension("js");

        jse.eval("println(new jasim.JSTest().toString)");

    }

    @Override
    publi开发者_开发技巧c String toString() {
        return "JSTest Object";
    }
}

This code will fail with the below exception:

Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "jasim" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1

How do I import my own classes into the ScriptEngine?


After looking at the Mozilla Rhino docs, the solution is either to use:

importPackage(Packages.jasim) within the script, or to use new Packages.jasim.JSTest()

This is not so clear in the Sun docs regarding the importPackage in the ScriptingEngine docs.


The same way you import javax.script.ScriptEngine;...

Just make sure your classes are in the CLASSPATH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜