views:

73

answers:

1

I'm using the Mozilla Rhino JavaScript emulator. It allows me to add Java methods to a context and then call them as if they were JavaScript functions. But I can't get it to work except when I use a static method.

The problem is this part of the documentation:

If the method is not static, the Java 'this' value will correspond to the JavaScript 'this' value. Any attempt to call the function with a 'this' value that is not of the right Java type will result in an error.

Apparently, my Java "this" value doesn't correspond with the one in JavaScript and I have no idea how to make them correspond. In the end, I'd like to create an instance in Java, and install a couple of methods from it in the global scope, so I can initialize the instance from Java but use it in my scripts.

Does anyone have some example code for this?

+2  A: 

What you can do is to bind a Java instance to the Javascript context, and then from Javascript that identifier will be a reference to the "real" Java object. You can then use it to make method calls from Javascript to Java.

Java side:

    final Bindings bindings = engine.createBindings();
    bindings.put("javaObject", new YourJavaClass());
    engine.setBindings(bindings, ENGINE_SCOPE);

Javascript:

    javaObject.methodName("something", "something");

Now that example assumes you're using the JDK 6 java.util.script APIs to get between Java and Rhino. From "plain" Rhino, it's a little different but the basic idea is the same.

Alternatively, you can import Java classes into the Javascript environment, and Rhino gives you Javascript-domain references to Java objects when you use Javascript "new" on references to Java classes.

Pointy
Thanks, that works. Since I use the Rhino API directly, the code is: `global.defineProperty( "javaObject", javaObject, ScriptableObject.CONST );` (although I'm not sure about the `CONST` - but the other attributes apply even less).
Aaron Digulla