Search code examples
gwtjsni

JSNI call a Java method with a Long param


I need to call a Java method from Javascript. So I defined the method:

private native void registerMethod() /*-{
    var self = this;
    $wnd.test = function(longParam) {
        [email protected]::test(Ljava/lang/Long;)(longParam);
    };
}-*/;

The Java method:

private void test(Long longParam) {
    GWT.log("Call to test with longParam =  " + longParam);
}

The JS call:

public static native void paypalClose() /*-{
    $wnd.alert(top.test);
    top.test(10);
    top.dgFlow.closeFlow();
    top.close();
}-*/;

The alert shows the Javascript function definition. If I call top.test(), it works but no param is passed. But if I call top.test(10) I get a null alert window.


Solution

  • Your method excepts a java.lang.Long, not a long, so you have to create an instance of Long. You could use @java.lang.Long::new or @java.lang.Long::valueOf, except you cannot use longs either in JSNI: https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsJSNI#important

    Because JavaScript numbers are strictly equivalent to Java doubles, you should use a double or java.lang.Double as an argument. Once in the Java world, you can cast the double to a long if you like, but not from/in JSNI.