1

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 - Function にキャストできます。その結果、次の解決策が役立ちました。

@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 } );
        }
});
4

1 に答える 1

0

次のコードで 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、CLASSPATH の で使用できる必要があります。

entity.handler = function(arg1, arg2) {
    console.println("Hello world from the JS handler");
    return 42;
}
于 2013-03-13T18:38:16.580 に答える