Implementing Java Interfaces from Javascript with Rhino

Media_httpdigitaltumb_upocz
Rhino
is a fairly awesome tool. You get the full capabilities of writing Javascript, plus the availability of the Java ecosystem. However, there is another awesome feature that I didn't know about until a few months ago when I read Todd Ditchendorf's post about thread synchronization in JS. You can actually implement Java interfaces from your Javascript. For example, let's say you want to override the toString method on a String object. I used his technique when I was writing a module to allow HTTP calls from the JS side of the house, on the server side. Below is the code that allows for asynchronous requests to be made. Very simple and very much like Todd's examples, but that is all it needs to do and it works beautifully.
...
ajax: function(url, data, callback, type) {
  var r = new Runnable() {
   run: function() {
    type = type || 'get';
    callback(axiom.HTTP[type](url, data));
   }
  };

  new Thread(r).start();
}
...
In essence it creates a new Runnable object, defines the run method, and then passes that Runnable object to a new Thread. While this code demonstrates the functionality with the Runnable object, you have the capability to do this with any other interface right from within your Javascript. It's really handy and took me a while to find so I thought I'd post something about it. Hope it helps.
Posted
Views | Favorited 0 Times

Comments (0)

Leave a comment...