javagwtjsni

How to cast a return value from javascript to java in GWT JSNI?


The JSNI method does not accept any parameters but return a Java Object type:

 public static native String nativeJSFuncGwt() /*-{
        $wnd.console.log($wnd.someJSFunc());
        return "" + $wnd.someJSFunc() + "" ;
    }-*/;


//someJSFunc returns { abc:xcv, def:asd}

I can see the value getting printed in the javascript console but java side is not able to understand the casting.

Is it because the native method does not accept any parameters ?

String tokenFromNativeJS = nativeJSFuncGwt(); // String value is null 

The documentation also is not clear enough in GWT.


Solution

  • I am posting here what finally worked for due to GWT version(2.4) constraint

    From GWT Doc:

    Outgoing Java type:

    Any other Java Object (including arrays)

    What must be passed:

    Java Object of the correct type that must have originated in Java code; Java objects cannot be constructed from “thin air” in JavaScript

    My code with modification would like:

    public static native MyObject nativeJSFuncGwt(MyObject obj) /*-{
    
       var xyz = $wnd.someJsFunc();
    
       obj.@package.name::setter1(Ljava/lang/String;)(xyz);
    
       return obj;
    
     }-*/;
    

    I wish documentation could have been more clear.