Hi
Can someone provide me an example on how to extend a java class in java script using Rhino's java adapter ?
Hi
Can someone provide me an example on how to extend a java class in java script using Rhino's java adapter ?
Depends on what you want to inherit. I find that if I use the JavaScript prototype for object “definitions” I get the static methods of Java objects only:
function test() {
this.hello = function() {
for(var i in this) {
println(i);
}
};
}
test.prototype= com.acme.app.TestClass; // use your class with static methods
// see the inheritance in action:
var testInstance=new test();
test.hello();
However, JavaScript allows you to do prototype assignments on object instances as well, so you could use a function like this, and get a more Java-like inheritance behaviour:
function test(baseInstance) {
var obj = new function() {
this.hello=function() {
for(var i in this) {
println(i);
}
};
};
obj.prototype=baseInstance; // inherit from baseInstance.
}
// see the thing in action:
var testInstance=test(new com.acme.TestClass()); // provide your base type
testInstance.hello();
Or use a function (e.g. init
) similar to the above function in the object itself:
function test() {
this.init=function(baseInstance) {
this.prototype=baseInstance;
};
this.hello=function() {
for(var i in this) {
println(i);
}
};
}
var testInstance=new test();
println(typeof(testInstance.prototype)); // is null or undefined
testInstance.init(new com.acme.TestClass()); // inherit from base object
// see it in action:
println(typeof(testInstance.prototype)); // is now com.acme.TestClass
testInstance.hello();
Since I am not a 100% sure that by Java Adapter you mean what I think it is, Java interfaces and such can be created with property lists (name = function()):
var runnable = new java.lang.Runnable({
run: function() { println('hello world!'); } // uses methodName: implementationFunction convention
};
java.awt.EventQueue.invokeLater(runnable); // test it
Or alternatively for single-method things like that:
function runnableFunc() { println('hello world!'); }
var runnable = new java.lang.Runnable(runnableFunc); // use function name
java.awt.EventQueue.invokeLater(runnable); // test it