简体   繁体   中英

Get returned value from java method with GWT's JSNI

I'm trying to get the returned value from a java method, but it returns something very strange: it returns the method itself written in javascript I think.

Here the code of the java method:

public String getNameToShow() {
        return "Chart number 1";
    }

and the javascript method:

 public native void drawJSChart(String divId, int a, String jsData) /*-{
            try {
                //First create a script where to paste the jsData
                var scriptID = this.@myPackage.MyClass::getNameToShow();
                console.log(scriptID);
                //Some code
            } catch (e) {
                console.error(e.message);
            }
        }-*/;

Thank you.

It returns js method because, you've asked for js method.

Invocation of java methods from JSNI code should look like this:

var scriptID = this.@myPackage.MyClass::getNameToShow(*)(); //notice second pair of braces

Basically to invoke java method from JSNI, you will need to place two pairs of braces. First defines method parameter types (in my example I've used * so it will match any parameter types), second is used to pass parameters into the method.

You have to pass the types of your Java function too. Writing it like this works:

package XXXXX.client;

import com.google.gwt.core.client.EntryPoint;

class _24_TestJSNIMethodCallback implements EntryPoint {
    public void onModuleLoad() {
        drawJSChart();
    }

    public String getNameToShow() {
        return "Chart number 1";
    }

    public native void drawJSChart() /*-{
        try {
            //First create a script where to paste the jsData 
            var scriptID = this
                    .@XXXXX.client._24_TestJSNIMethodCallback::getNameToShow()();
            $wnd.alert(scriptID);
            //Some code 
        } catch (e) {
            console.error(e.message);
        }
    }-*/;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM