Creating generic two-dimensional array using Class object

12,211

Solution 1

Same as How to create a generic array in Java? but extended to 2D:

import java.lang.reflect.Array;

public class Example <T> {

    private final Class<? extends T> cls;

    public Example (Class<? extends T> cls) {
        this.cls = cls;
    }

    public void arrayExample () {
        // a [10][20] array
        @SuppressWarnings("unchecked")
        T[][] array = (T[][])Array.newInstance(cls, 10, 20);
        System.out.println(array.length + " " + array[0].length + " " + array.getClass());
    }

    public static final void main (String[] args) {
        new Example<Integer>(Integer.class).arrayExample();
    }

}

Note after reading JAB's comment above: To extend to more dimensions, just add []'s and dimension parameters to newInstance() (cls is a Class, d1 through d5 are integers):

T[] array = (T[])Array.newInstance(cls, d1);
T[][] array = (T[][])Array.newInstance(cls, d1, d2);
T[][][] array = (T[][][])Array.newInstance(cls, d1, d2, d3);
T[][][][] array = (T[][][][])Array.newInstance(cls, d1, d2, d3, d4);
T[][][][][] array = (T[][][][][])Array.newInstance(cls, d1, d2, d3, d4, d5);

See Array.newInstance() for details.

Solution 2

You have to use reflection, but it's possible: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html#newInstance%28java.lang.Class,%20int...%29

Creates a new array with the specified component type and dimensions.

Share:
12,211
Krzysztof Stanisławek
Author by

Krzysztof Stanisławek

Updated on June 15, 2022

Comments

  • Krzysztof Stanisławek
    Krzysztof Stanisławek almost 2 years

    I have generic type with Class<T> object provided in constructor. I want to create two-dimensional array T[][] in this constructor, is this however possible?