5

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
    public 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?

1
  • A code is worth 1000 words of explaining it .Thumbs up Commented Jan 11, 2013 at 10:18

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The documentation notes that "The class provides additional importPackage() and importClass() global functions for scripts but their extensive usage has tendency to pollute the global name space with names of Java classes and prevents loaded classes from garbage collection." You would probably be better off using JavaImporter.
-4

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

Just make sure your classes are in the CLASSPATH

1 Comment

they are in the classpath, but not visible in the JavaScript runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.