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?
The commented code seems to be the source of problem, since it comments out even the method name
myMethod
remove this line and rerun your code
If you want to preserve your comment then instead of single line comment (//) use multi line comment (/**/)