简体   繁体   English

使用 GWT 的 JSNI 从 java 方法获取返回值

[英]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.我试图从 java 方法获取返回值,但它返回了一些非常奇怪的东西:它返回了我认为在 javascript 中编写的方法本身。

Here the code of the java method:这里是 java 方法的代码:

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

and the javascript method:和 javascript 方法:

 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.它返回 js 方法,因为您已经要求 js 方法。

Invocation of java methods from JSNI code should look like this:从 JSNI 代码调用 java 方法应该如下所示:

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.基本上从 JSNI 调用 java 方法,你需要放置两对大括号。 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.您也必须传递 Java function 的类型。 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);
        }
    }-*/;

}

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

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