GWT: how to pass Java arrays to JavaScript native methods?

I have a string array, and now I want to pass it to the jsni function I tried to use jsarraystring in GWT, but I found that it cannot be initialized directly because it has no visible constructor So how do I pass my string array to the jsni function and use it in my JavaScript code? The code is as follows:

public void callJSNI() {
    String[] stringArray = xxx;

    //How should I convert the array into a JSNI-readable format here?
}

private native void JSNIMethod(JsArrayString array) /*-{
    //some code to use the array in javascript
}-*/

Solution

The API does not provide a simple method. You must create a utility method that will:

>Create a new jsni array > iterate over the parameters of the Java array and populate the jsni array

Something like this:

public static JsArrayString toJsArray(String[] input) {
    JsArrayString jsArrayString = createEmptyJsArrayString();
    for (String s : input) {
        jsArrayString.push(s);
    }
    return jsArrayString; 
}

private static native JsArrayString createEmptyJsArrayString() /*-{
    return [];
}-*/;

As OP suggests, we can certainly skip native initialization and use jsarraystring createArray().

Now we can get rid of native initialization, so our code is simplified to:

public static JsArrayString toJsArray(String[] input) {
JsArrayString jsArrayString = JsArrayString.createArray().cast();
    for (String s : input) {
        jsArrayString.push(s);
    }
    return jsArrayString; 
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>