Passing javascript parameter from external javascr

2019-07-14 02:10发布

问题:

An external javascript gives a number that should be handed over to Java method named mycallback.

I have defined:

Java:

class MyClass {
    public static void mycallback(JavaScriptObject number) {
        // do something with the number
    }
}

Javascript:

$wnd.callback = $entry(@com.package.MyClass::mycallback(Lcom/google/gwt/core/client/JavaScriptObject));

And the Javascript call is:

$wnd.callback(number_from_external_javascript);

But I get error:

JS value of type number, expected com.google.gwt.core.client.JavaScriptObject

And my ultimate goal is to have a java method with parameter type of Integer, not of JavascriptObject. I just thought GWT should wrap javascript objects in JavascriptObject, but it seems it won't.

GWT version is 2.4.

回答1:

GWT will automatically cast a JS Number value to any Java number primitive type (int, double, etc.), JS String to Java String, and JS Boolean to Java boolean. It'll never pass them as JavaScriptObjects.

If the number cannot be null, then just declare your callback with an int argument. If it can be null, then you'll have to explicitly create an Integer instance, something like:

$wnd.callback = $entry(function(n) {
      if (number != null) {
         // box into java.lang.Integer
         number = @java.lang.Integer::valueOf(I)(n);
      }
      @com.packge.MyClass::mycallback(Ljava/lang/Integer;)(number);
   });

Alternatively, I think you can pass a JS number as a JavaScriptObject if it's a Number object rather than a Number value, so this might work:

$wnd.callback = $entry(function(n) {
      n = new Number(n); // "box" as a Number object
      @com.packge.MyClass::mycallback(Lcom/google/gwt/core/client/JavaScriptObject;)(n);
   });


回答2:

What about using the gwt-exporter generator to expose your gwt code to js, so you dont have to deal with jsni and you could benefit of the nice features it has (complex objects, arrays, closures, overlays, doclet, etc)

Using gwt-exporter your class just have to implement Exportable and use an annotation to expose your method.

public static class MyClass implements Exportable {
 @Export("$wnd.mycallback")
 public static void mycallback(long number) {
  Window.alert("" + number);
 }
}

Add this line to your onmoduleload and leave the compiler to do the work

public void onModuleLoad() {
  ExporterUtil.exportAll();
}

Then you can use the method as you said

<script>
  window.mycallback(1234)
</script>


标签: gwt jsni