I'm trying to test out JavaScript through Java using simple Nashorn examples, and I'm just not understanding why I can't access a method of my own class from a JS call.
First, the class I want to work with:
package myPackage;
public class myClass
{
Object internalObj;
static boolean test()
{
return true;
}
boolean storeObject(Object obj)
{
internalObj = obj;
return true;
}
String whatObjectType()
{
return internalObj.getClass().toString();
}
}
Then, the code that is to provide scripting calls:
package myPackage;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class myTester
{
public static void main( String[] args )
{
System.out.println(">> Script Testing");
//test out my class
System.out.println(myClass.test());
myClass myObj = new myClass();
myObj.storeObject("test");
System.out.println(myObj.whatObjectType());
//now try the same from javascript
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
String myScript ="var myJSClass = Java.type('myPackage.myClass');"
+ "var myJSObj = new myJSClass();"
+ "print(myJSObj.test());";
try
{
js.eval(myScript);
} catch (ScriptException e)
{
e.printStackTrace();
}
}
}
Everything is well and good until the evaluation of myJSObj.test(), which craps out. Here's the output:
>> Script Testing
true
class java.lang.String
javax.script.ScriptException: TypeError: myJSObj.test is not a function in <eval> at line number 1
Most of the Nashorn intro material shows similar examples, except they all work. What am I doing wrong?