如何使用Rhino在Javascript中将Java类中的方法添加为全局函数? [英] How can I add methods from a Java class as global functions in Javascript using Rhino?
问题描述
我有一个简单的Java类,它有一些方法:
I have a simple Java class that has some methods:
public class Utils {
public void deal(String price, int amount) {
// ....
}
public void bid(String price, int amount) {
// ....
}
public void offer(String price, int amount) {
// ....
}
}
我想创建这个类的实例并允许Javascript代码直接调用这些方法,如下所示:
I would like to create an instance of this class and allow the Javascript code to call the methods directly, like so:
deal("1.3736", 100000);
bid("1.3735", 500000);
我现在唯一可以解决的方法是使用
The only way I could figure out for now was to use
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.put("utils", new Utils());
然后使用 utils.deal(...)
在Javascript代码中。我也可以在Javascript中为每个方法编写包装函数,但应该有一种更简单的方法来自动为类的所有公共方法执行此操作。
and then use utils.deal(...)
in the Javascript code. I can also write wrapper functions in Javascript for each method, but there should be a simpler way to do this automatically for all the public methods of a class.
推荐答案
我对Rhino并不熟悉,但这样的事情应该有效:
I'm not real familiar with Rhino, but something like this should work:
for(var fn in utils) {
if(typeof utils[fn] === 'function') {
this[fn] = (function() {
var method = utils[fn];
return function() {
return method.apply(utils,arguments);
};
})();
}
}
只需循环遍历 utils
,对于每个函数,创建一个调用它的全局函数。
Just loop over the properties of utils
,and for each one that is a function, create a global function that calls it.
编辑:我让这个工作在一个Groovy脚本,但我必须在绑定中设置utils,而不是在代码中设置引擎:
I got this working in a Groovy script, but I had to set utils in the bindings, not on the engine like in your code:
import javax.script.*
class Utils {
void foo(String bar) {
println bar
}
}
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.eval("""
for(var fn in utils) {
if(typeof utils[fn] === 'function') {
this[fn] = (function() {
var method = utils[fn];
return function() {
return method.apply(utils,arguments);
};
})();
}
}
foo('foo'); // prints foo, sure enough
""",new SimpleBindings("utils":new Utils()))
这篇关于如何使用Rhino在Javascript中将Java类中的方法添加为全局函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!