On Friday, December 21, 2012 8:39:34 PM UTC+1, Sebastián Gurin wrote:
Hi all. I'm porting some javascript libraries to GWT and in this thread I hope I can share and learn best ways of accessing Js native arrays from java language.
I try to add the minimun overhead so I'm using GWT's JsArray, JsArrayMixed, JsArrayString, etc for referencing arrays whenever I can. But this is not so friendly for a Java programmer accustomed to work with real java arryas (String[]) or with java.util.Collection API.
The first thing I thought of was convert js arrays to Java arrays. Unfortunately i didn't found a way of doing this without (linear overhead);
public static JsArrayNumber toJsArrayDouble(double[]a) {
That reverse operation allows using a for loop to iterate on a JsArray*, e.g.: for (double : toArray(myJsArrayNumber)) { … }
Now I'm experimenting on wrapping a Js Array into a java Collection. For this I made a simple Java class that extends java.util.AbstractCollection [0] and wrapps a pure js array. So from jsni code now I can return Java Collections instead JsArray like types and the final user of my libs can write java statements like for(String s : myOverlay.getArrayProp()) {..}.
Also this solution adds very few (constant) overhead. So now I'm using two getters for js arrays, one that return the real js array object using GWT's JsArray* and other that return a Java Collection:
/**
* Returns 'columns' property (JavaScript array)
* @return
*/
public native final JsArrayString columns() /*-{
return this["columns"];
}-*/;
/**
* Returns 'columns' property (Java Collection)
* @return
*/
public native final Collection<String> getColumns() /*-{
return @org.sgx.test1.client.JsUtil::toJavaCollection(Lcom/google/gwt/core/client/JavaScriptObject;)(this["columns"]);
}-*/;
FYI, I would have written it:
public final Collection<String> getColumns() {
return JsUtils.toJavaCollection(columns());
}
I would like to hear what others in the same situation do. Use JsArray* GWT's classes vs more Java friendly API ??? Thanks in advance any suggestion or comment is most appreciated.
[0] - Source code for my Java Collection class wrapper
import java.util.AbstractCollection;
import java.util.Iterator;
import com.google.gwt.core.client.JavaScriptObject;
/**
* a Java Friendly way of working with Js Arrays using the Java.util.Collection API
* @author sg
*
* @param <T>
*/
public class JsArrayCollection<T> extends AbstractCollection<T> {
Maybe we should have something like that in GWT proper. There hasn't been much demand AFAICT, and if we start going that way, people will likely ask for java.util.List rather than java.util.Collection.