1

I am having some difficulty creating an array of a Class, where the Class is of a generic type.

Let's take an example function, addOverlay, as follows (assume mapSize is a static class variable):

public void addOverlay(Class<?> dataType) {
    dataType[][] d = new dataType[mapSize][mapSize];
    overlayMap.add(new Class[mapSize][mapSize]);
}

I get the error, dataType cannot be resolved to a type. This in and of itself doesn't make sense to me, since dataType holds a class type. Still, I tried to insert it directly, with the statement (which gives the same error as before):

overlayMap.add(new dataType[mapSize][mapSize]);

And so on, and so on. I have also tried to use dataType.getClass().

Is there a way in Java to create an array of a class, where the class is a generic type?

2 Answers 2

2

You should be clear that dataType just is an instance of Class class, which only holds the metadata about certain class. In your case, you can modify your method like this:

public void addOverlay(Class<?> dataType) {
    Object subArray = Array.newInstance(dataType, mapSize);
    Object array = Array.newInstance(subArray.getClass(), mapSize);
    for (int i = 0; i < mapSize; i++) {
        Array.set(array, i, subArray);
    }
    overlayMap.add(array);
}
Sign up to request clarification or add additional context in comments.

Comments

0

'dataType' already is a class, so calling getClass() on it isn't the answer (you will just get Class.class). You can do this with 'java.lang.ref.Arrays.newArray()'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.