Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing javascript parameter from external javascript to java

Tags:

gwt

jsni

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.

like image 705
egaga Avatar asked Mar 26 '26 14:03

egaga


2 Answers

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);
   });
like image 148
Thomas Broyer Avatar answered Mar 29 '26 02:03

Thomas Broyer


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>
like image 44
Manolo Carrasco Moñino Avatar answered Mar 29 '26 03:03

Manolo Carrasco Moñino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!