简体   繁体   English

如何编写从服务器端 JavaScript 调用的 Java 方法,该方法将 JS 回调函数作为参数?

[英]How do I write a Java method, to be called from server side JavaScript, that takes a JS callback function as an argument?

I'm trying to write a Java API that will be called from server side JavaScript running under the JDK 7 JS engine.我正在尝试编写一个 Java API,它将从在 JDK 7 JS 引擎下运行的服务器端 JavaScript 调用。 The idea is to give consumers the ability to write JS code like below, registering a callback that is later executed by another call to a Java method:这个想法是让消费者能够编写如下 JS 代码,注册一个回调,稍后由另一个对 Java 方法的调用执行:

myJavaObj.registerCallback(function (param) {
  // do stuff here
});
myJavaObj.methodThatTriggersCallback();

Here is some test code I'm using:这是我正在使用的一些测试代码:

import javax.script.Invocable;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JSTestClient {

    private String successCallback;

    public void handleSuccess(String successCallback) {
        this.successCallback = successCallback;
    }

    public void doStuff() throws ScriptException, NoSuchMethodException {
        ScriptEngineManager manager = new ScriptEngineManager();
        Invocable engine = (Invocable) manager.getEngineByName("JavaScript");
        engine.invokeFunction(successCallback, "TEST SUCCESS");
    }
}
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        String js =
                "var client = new Packages.JSTestClient();\n" +
                "client.handleSuccess(function (response) {\n" +
                "  java.lang.System.out.println(response);\n" +
                "});\n" +
                "client.doStuff();";
        try {
            engine.eval(js); // Expecting this to output "TEST SUCCESS"
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

But when I run this I get a java.lang.NoSuchMethodException because it is interpreting the string:但是当我运行它时,我得到一个 java.lang.NoSuchMethodException 因为它正在解释字符串:

function (response) {
    java.lang.System.out.println(response);
}
as a function name. 作为函数名。 Is there a way to create a callback like this or do I need to use some other convention? 有没有办法创建这样的回调,还是需要使用其他约定?

Your handleSuccess method takes a String as the argument, but you're calling it with a JavaScript function object.您的handleSuccess方法将String作为参数,但您正在使用 JavaScript function对象调用它。 You need to change it to accept a Function .您需要更改它以接受Function

Since you're using Java 7, you are using the modifiedMozilla Rhino engine, where the implementation classes were moved from package org.mozilla.javascript to sun.org.mozilla.javascript.internal .由于您使用的是 Java 7,因此您使用的是经过修改的Mozilla Rhino引擎,其中实现类从包org.mozilla.javascript移动到sun.org.mozilla.javascript.internal

To get your code running, replace the JSTestClient with this:要运行您的代码,请将JSTestClient替换为:

import sun.org.mozilla.javascript.internal.Context;
import sun.org.mozilla.javascript.internal.Function;

public class JSTestClient {

    private Function successCallback;

    public void handleSuccess(Function successCallback) {
        this.successCallback = successCallback;
    }

    public void doStuff() {
        this.successCallback.call(Context.getCurrentContext(), null, null,
                                  new Object[] { "TEST SUCCESS" });
    }
}

Be aware that Java 8 changed to the Nashorn engine, and the code for interacting with Nashorn is entirely different.请注意,Java 8 更改为 Nashorn 引擎,与 Nashorn 交互的代码完全不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写一个称为countDots(x)的函数,该函数将字符串作为参数并返回包含的点数(。)。 - How do I write a function called countDots(x) that takes a string as an argument and returns the number of dots (.) it contains 除了服务器端回调之外,我如何调用javascript函数? - How do I call a javascript function in addition to a server-side callback? 如何编写服务器端的node.js / express方法? - How do I write a server side node.js / express method? 如何编写客户端Java脚本以在Node JS服务器上运行 - How do I write a client side Java script to run on a Node JS server 如何编写一个接受回调函数的jQuery插件方法? - How do I write a jQuery plugin method that accepts a callback function? 如何将函数编写为事件处理程序和带参数的可调用函数? - How do I write a function as both an event handler and a callable function that takes an argument? 我可以在java中使用来自服务器回调的javascript函数吗? - Can I use javascript function from server callback in java? 如何从 javascript 调用 node.js 服务器端方法? - How to call node.js server side method from javascript? 我该如何编写称为validate(z)的函数,该函数将字符串作为参数,如果包含1个“ @”符号和至少1个“。”,则返回true;否则返回false - How can i write function called validate(z) which takes a string as argument & return true if contain 1 “@” symbol & at least 1 “.” & false otherwise 如何从javascript中的回调函数返回变量? - How do I return a variable from a callback function in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM