Storm-
Storm-

Reputation: 147

Java Reflection (unsure on how to word this, look inside for more info)

I need to make a Deep Copy of a 2D array. I know how to do this

int[][] a = new int[original.length][];
for(int i = 0; i < original.length; i++) {
    a[i] = Arrays.copyOf(original[i], original[i].length);
}

However, I'm now in a position where I don't know the Object type of the Array I'm copying. I have a method like so

public Object[] copy(Object[] original) {}

Which should return a deep copy of original IF it is an array of arrays. If the method is given a int[][], I can't cast that to an Object for the array (since it's a primitive type).

Currently, I can check to see if 'original' is a 2D array like so

if(original==null||original.length==0||!original.getClass().getName().startsWith("[")) {
    return null;
}

But now I'm unsure on how to do a Deep copy of an array of an unknown type. I assume I'll be needing to use Java Reflection, although I'm not 100% sure on how I would go about this.

For reference, this was my original attempt

public Object[] copy(Object[] original) {
    if(original==null||original.length==0||!original[0]getClass().getName().startsWith("[")) {
        return null;
    }
    Object[][] returnArray = new Object[original.length][];
    for(int i = 0; i < original.length; i++) {
        returnArray[i] = Arrays.copyOf((Object[]) original[i], ((Object[]) original[i]).length);
    }
    return returnArray
}

Unfortunately, int[] cannot be casted to Object[] (or any primitive[]).

Upvotes: 0

Views: 63

Answers (1)

Turo
Turo

Reputation: 4914

I could think of a solution with a switch for the primitives, like Arrays has a copyOf-function for every primitive:

public static Object[] copyDeep(Object[] original) {
    Object[] newArray = Arrays.copyOf(original, original.length);
    if ( newArray.getClass().getComponentType().isArray()) {
        for (int i = 0; i < newArray.length ; i++) {
            switch (newArray[i].getClass().getComponentType().getSimpleName()) {

            case "int" : newArray[i] = Arrays.copyOf( (int[])newArray[i],Array.getLength(newArray[i]));
                break;

            case "float" : newArray[i] = Arrays.copyOf( (float[])newArray[i],Array.getLength(newArray[i]));
                break;
            // TODO other primitives

            default: newArray[i] = Arrays.copyOf( (Object[])newArray[i],Array.getLength(newArray[i]));
            }
        }
    }
    return newArray;
}

`

Upvotes: 1

Related Questions