-1

I'm working on getting (JavaScript) scripting to work in Java.

I have a program in JavaScript, defined in my Java program (along with instances of all the necessary script engine related things) like so:

static ScriptEngineManager engineManager = new ScriptEngineManager();
static ScriptEngine jsengine = engineManager.getEngineByName("js");
static Invocable jsinvoke = (Invocable) jsengine;


static String program =

    "//importPackage(javax.swing);" +
    "function myMethod(x, y) {" +
        "return x+y;" +
    "}";

At the start of the program I do call this, which works without complaint:

    try {
        jsengine.eval(program);
    } catch(ScriptException e) {e.printStackTrace();}

Then, I call myMethod with this:

    try {
        jsinvoke.invokeFunction("myMethod", x, y);
    } catch(ScriptException se) {
        se.printStackTrace();
    }
    catch(NoSuchMethodException nsme) {
        nsme.printStackTrace();
    }

It gives the error java.lang.NoSuchMethodException: no such method: myMethod. It clearly exists in the JavaScript, so what did I do wrong?

1 Answers1

3

The commented code seems to be the source of problem, since it comments out even the method name myMethod

//importPackage(javax.swing);

remove this line and rerun your code

If you want to preserve your comment then instead of single line comment (//) use multi line comment (/**/)

mprabhat
  • 19,229
  • 7
  • 42
  • 62
  • Or he could just comment out the entire line in Java instead in his Javascript string. Same effect, minus the bugs. – Travis Webb Apr 25 '12 at 03:30
  • Yeah, I can't believe I missed that. By the way, is it possible to import custom libraries into Rhino? Because it doesn't seem to find library JARs I have installed that I know are working because I can `import` them with Java just fine. (or should I make this another question? :P) –  Apr 25 '12 at 04:04
  • Nevermind: http://stackoverflow.com/questions/4090155/calling-java-method-from-javascript-using-scriptengine worked perfectly. –  Apr 25 '12 at 04:14