With Mustang's JavaScript engine, there are 4 ways to implement Java interface in script:
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.
var x = { run: function() { print('hello') } }
var r = engine.getInterface(java.lang.Runnable, x);
r.run();
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.
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 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.