0

I have problems accessing Java classes in JavaScript. Calling a code snippet

var String = Java.type("java.lang.String");

from Java via javax.script.ScriptEngine, yields follwing Error

Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "Java" is not defined. (path/to/string.js#1) in path/to/string.js at line number 1
    at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:156)
    at main.JsTest.main(JsTest.java:55)

Using non-Java classes in the script works fine, e.g. var value = a + b, where a and b are defined in a javax.script.ScriptContext.

This is the Java class that executes the script.

JsTest.java

public class JsTest
{
  public static void main(String[] args) throws Exception
  {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine se = sem.getEngineByExtension("js");

    String script = "path/to/string.js";
    File scriptFile = new File(script);
    FileReader fr = new FileReader(scriptFile);

    se.put(ScriptEngine.FILENAME, script);

    ScriptContext sc = new SimpleScriptContext();
    se.eval(fr, sc);
  }
}

1 Answer 1

2

I have no idea where your Java.type is coming from, but the official documentation uses Packages.java or just java.

So your line should probably look like

var String = Packages.java.lang.String;
Sign up to request clarification or add additional context in comments.

1 Comment

Apparently I mixed in Nashorn syntax.

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.