I've found a few questions about shuffling class definitions between Javascript and Java using Mozilla's Rhino. I've gotten far enough that this works:
Javascript:
new JavaAdapter(MyClass, {foo: function(){return 'Hello!';}});
Java
String script = // the above stuff
Object o = context.evaluateString(scope, script, "UserScript", 1, null);
MyClass mc = (MyClass) Context.jsToJava(o, MyClass.class);
mc.foo(); // returns "Hello!"
That blew me away, but I'd like to move the JavaAdapter construction from the Javascript to the Java side. I'm writing a framework where users will define logic in Javascript, and the less boilerplate they have to paste in the happier they'll be.
Ideally, I could do this:
Javascript:
{foo: function(){return 'Hello!';}};
Java
String script = // the above stuff
Object o = context.evaluateString(scope, script, "UserScript", 1, null);
MyClass mc = new JavaAdapter(MyClass.class, o);
mc.foo(); // returns "Hello!"
but as far as I can tell the JavaAdapter constructor doesn't take any parameters, there's no documentation for the class anywhere (for example, it's not here), and I haven't found any static methods (e.g. on Context
or ScriptableObject
) that create such a class. I also tried Context.jsToJava(o, MyClass.class)
, but that threw an exception.
JavaInterface
'd "subclass" can call aprotected
superclass method, but not access aprotected
superclass field / variable. I guess that's expected behavior? I just added stupid one-line getters and setters, but it seems like it shouldn't be necessary. – Czar