X

Sundararajan's Weblog

  • Java
    October 31, 2005

Implementing Java interfaces in JavaScript

Guest Author
With Mustang's JavaScript engine, there are atleast 4 ways to implement Java interfaces in script:
  1. JavaAdapter function

    var r = new JavaAdapter(java.lang.Runnable,
    {
    run: function() { print('hello'); }
    });
    r.run();

    This feature may also be used with Java anonymous class-like syntax as shown below:

    var r = new java.lang.Runnable() {
    run: function() {
    print('hello')
    }
    };
    r.run();

    Unlike, Rhino's JavaAdapter, Mustang's JavaAdapter does not support implementing
    multiple Java interfaces. Also, extending a super class is not allowed.
  2. using engine variable in jrunscript (or exposing
    ScriptEngine object as global variable and using it in script)

    var x = { run: function() { print('hello') } }
    var r = engine.getInterface(x, java.lang.Runnable);
    r.run();
  3. pass script function whenever a Java interface type parameter is required!
    (this works from Rhino 1.6R2 onwards -- so, you have to wait for Mustang build 59 or above for this)

    function run() {
    print('hello');
    }
    // script function is wrapped automatically
    var t = new java.lang.Thread(run);
    t.start();

    This feature works only if all the methods of the interface have the same signature or there is only one method in the interface. For interface with multiple
    methods, script function receives the name of the method as first parameter.
  4. using JSAdapter
    and JavaAdapter.

    function Invoker(obj) {
    return new JSAdapter() {
    __has__: function(name) {
    return true;
    },
    __get__: function(name) {
    return function() {
    return obj.invoke(name, arguments);
    }
    }
    }
    }
    var r = {
    invoke: function(name, args) {
    print(name + " called");
    }
    };
    var x = new JavaAdapter(java.lang.Runnable, Invoker(r));
    x.run(); // this calls r.invoke('run');

    This scheme works even if interface methods don't have identical signature. But,
    invoke method has to handle variable number of arguments passed as args array
    (second argument). The first argument is the name of the interface method.

Join the discussion

Comments ( 1 )
  • vasudev Monday, November 27, 2006
    i can not fine addGeneratedToClassLoader method in rhino 1.6R4. how is a class file generated by compiletoclassfiles, run in a java code?
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.