Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT to Javascript conversion

Tags:

javascript

gwt

In javascript console if I do this,

   a = [1,2,3]
   Object.prototype.toString.call(a) // gives me "[object Array]"
   typeof a  // gives me "object"

If I create an arraylist in GWT and pass it to a native method and do this,

// JAVA code
   a = new ArrayList<Integer>();
   a.push(1);
   a.push(2);

   //JSNI code
    Object.prototype.toString.call(a) // gives me "[object GWTJavaObject]"
    typeof a // returns "function"

What exactly is the difference between the both? Is GWTJavaObject exactly similar to Array?

Why do typeof return "object" in pure javascript but "function" in GWT?

Summary question is, what exactly are the GWT objects converted to in Javascript? Full code is here.

      public void onModuleLoad()
        {
                List<Integer> list = new ArrayList<Integer>();
            list.add( new Integer( 100 ) );
            list.add( new Integer( 200 ) );
            list.add( new Integer( 300 ) );

            Window.alert(nativeMethodCode( list ));
                Window.alert(nativeMethodCode2( list ));
        }

        public static final native Object nativeMethodCode( Object item )
        /*-{
            return Object.prototype.toString.call(item);
        }-*/;

        public static final native Object nativeMethodCode2( Object item )
        /*-{
            return typeof item;
        }-*/;
like image 593
LPD Avatar asked Jan 11 '13 07:01

LPD


1 Answers

An ArrayList in GWT is not translated to a pure JS array: it's a class extending AbstractList and implementing a bunch of interfaces, and this information should be kept when translated to JS so that instanceof checks (in your Java code; e.g. instanceof List or instanceof RandomAccess) still work as expected. An ArrayList is thus implemented as a wrapper around a JS array, see https://code.google.com/p/google-web-toolkit/source/browse/tags/2.5.0/user/super/com/google/gwt/emul/java/util/ArrayList.java.

Note that a Java array is translated to a JS array, but be very careful about what you do to it in JSNI as you could break further Java assumptions (e.g. that an array has a fixed size).

like image 165
Thomas Broyer Avatar answered Sep 20 '22 13:09

Thomas Broyer