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;
}-*/;
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With