我将函数从JavaScript文件传递到Java代码中。JavaScript函数如下所示:
entity.handler = function(arg1, arg2) {
//do something
};在Java代码中,该类实现了Scriptable接口。当我调用JavaScript时,实际上在Java中调用了以下方法:
Scriptable.put(java.lang.String s, org.mozilla.javascript.Scriptable scriptable, java.lang.Object o)
在我的案例中:
S=‘处理程序’;
scriptable -类型为com.beanexplorer.enterprise.operations.js.ScriptableEntity的对象
O-实际上是一个函数,它的类型是org.mozilla.javascript.gen.c15,( o instanceof Scriptable )在调试器中返回true。
在Scriptable.put()方法实现中,我希望将操作委托给'o‘对象:
SomeClass.invoke( new SomeListener(){
@override
public void someAction(int arg1, float arg2) {
//here I need to delegate to the 'o' object.
//do something looked like:
o.call(arg1, arg2); // have no idea how to do it, if it's possible.
}
}我该怎么做呢?我找不到我的情况所需的任何示例。
谢谢。
编辑,解决方案:实际上o-可以转换为函数。因此,以下解决方案起到了帮助作用:
@Override
put(java.lang.String s, org.mozilla.javascript.Scriptable scriptable, java.lang.Object o) {
....
final Function f = ( Function )o;
final SomeInterface obj = new ...;
obj.someJavaMethod( Object someParams, new SomeJavaListener() {
@Override
public void use(Object par1, Object par2) throws Exception {
Context ctx = Context.getCurrentContext();
Scriptable rec = new SomeJavaScriptableWrapperForObject( par1);
f.call( ctx, scriptable, scriptable, new Object[] { rec, par2 } );
}
});发布于 2013-03-14 02:38:17
我设法通过以下代码运行了您的Javascript:
public class Main {
public static void main(String[] args) {
new ContextFactory().call(new ContextAction(){
@Override
public Object run(Context ctx) {
Scriptable scope = ctx.initStandardObjects();
try {
Scriptable entity = ctx.newObject(scope);
scope.put("console", scope, Context.javaToJS(System.out, scope));
scope.put("entity", scope, entity);
ctx.evaluateReader(
scope,
new InputStreamReader(Main.class.getResourceAsStream("/handler.js")),
"handler.js", 1, null);
Function handler = (Function) entity.get("handler", entity);
Object result = handler.call(ctx, scope, scope, new Object[] {"Foo", 1234});
System.out.println("Handler returned " + result);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return null;
}
});
}
}以下脚本必须在类路径上的handler.js中可用:
entity.handler = function(arg1, arg2) {
console.println("Hello world from the JS handler");
return 42;
}https://stackoverflow.com/questions/15389067
复制相似问题