Can someone provide me an example on how to extend a java class in java script using Rhino's java adapter ?
For anyone else who might come across this, there's a decent example here (the author uses it to extend awt.Canvas
).
var smileyCanvas = new JavaAdapter(awt.Canvas, {
paint: function (g) {
var size = this.getSize();
var d = Math.min(size.width, size.height);
var ed = d / 20;
var x = (size.width - d) / 2;
var y = (size.height - d) / 2;
// draw head (color already set to foreground)
g.fillOval(x, y, d, d);
g.setColor(awt.Color.black);
g.drawOval(x, y, d, d);
// draw eyes
g.fillOval(x+d/3-(ed/2), y+d/3-(ed/2), ed, ed);
g.fillOval(x+(2*(d/3))-(ed/2), y+d/3-(ed/2), ed, ed);
//draw mouth
g.drawArc(x+d/4, y+2*(d/5), d/2, d/3, 0, -180);
}
});
There's more information on MDN, including a brief explanation and calling syntax example.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With