有人能为我提供一个如何使用Rhino的java适配器在java脚本中扩展java类的示例吗?
答案 0 :(得分:6)
对于其他可能遇到此问题的人,有一个不错的例子here(作者使用它来扩展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);
}
});
有more information on MDN,包括简要说明和调用语法示例。
答案 1 :(得分:2)
由于我不是100%确定通过Java Adapter你的意思是我认为它,Java接口等可以使用属性列表(name = function())创建:
var runnable = new java.lang.Runnable({
run: function() { println('hello world!'); } // uses methodName: implementationFunction convention
};
java.awt.EventQueue.invokeLater(runnable); // test it
或者对于像这样的单一方法:
function runnableFunc() { println('hello world!'); }
var runnable = new java.lang.Runnable(runnableFunc); // use function name
java.awt.EventQueue.invokeLater(runnable); // test it
答案 2 :(得分:1)
取决于您想要继承的 。我发现如果我将JavaScript原型用于对象“定义”,我只得到Java对象的静态方法:
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();
但是,JavaScript允许您对对象实例进行原型分配,因此您可以使用这样的函数,并获得更像Java的继承行为:
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();
或者在对象本身中使用与上述函数类似的函数(例如init
):
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();
答案 3 :(得分:0)
E.g。在Rhino中开始一个主题:
function startThread(funcOfThread) {
var someClass = { run: funcOfThread }; // Rhino syntax for new class with overwritten method
var r = new java.lang.Runnable(someClass);
var t = new java.lang.Thread(r);
t.start();
}
function UDP_Client() {
while (1)
java.lang.Thread.sleep(100);
}
startThread(UDP_Client);