arraysgwtjsni

Creating New Array with Class Object in GWT


I would like to create a new array with a given type from a class object in GWT.

What I mean is I would like to emulate the functionality of

java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)

The reason I need this to occur is that I have a library which occasionally needs to do the following:

Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();

This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.

I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation, there exists an inaccessible static method for creating a class object for an array.

Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.

In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.


Solution

  • The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.

    public class Foo extends Bar<Baz> {
    
        public Foo()
        {
            super(new Baz[0]);
        }
    ...
    }
    

    Baz:

    public abstract class Baz<T>
    {
        private T[] emptyArray;
    
        public Baz(T[] emptyArray)
        {
            this.emptyArray = emptyArray;
        }
    ...
    }
    

    In this case the Bar class can't directly create new T[10], but we can do this:

    ArrayList<T> al = new ArrayList<T>();
    
    // add the items you want etc
    
    T[] theArray = al.toArray(emptyArray);
    

    And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).