0

I need to create an array at running time according to the values of the input array tableParameter.

An example of my code is as follows:

int[] tableParameter = new int[dimension + 1];
tableParameter[0] = N;
for(int i = 1; i < tableParameter.length; i++)
    tableParameter[i] = i;
Object myArray = Array.newInstance(int.class, tableParameter);
//set the index 1 of the array with the value 100
Array.setInt(myArray, 1, 100);

The exception occurs in the last line of the code above:

Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array

But when I used the

System.out.println(myArray.getClass().getCanonicalName());

to verify the class of myArray, it prints out int[][][][], which means myArray is definitely an array type.

So why the JVM throws the exception that myArray is not an array?

1 Answer 1

4

It may be a misleading exception, but it's definitely correct to complain. If the array is an int[][][][], it doesn't make sense to set the element at index 1 to value 100. For example, this won't compile:

int[][][][] array = new int[1][1][1][1];
array[0] = 100; // Nope...

You can only set an element to an int if it's an actual int[]. So if dimension is 0 (meaning you end up with a 1-dimensional array) and if N is 2 or more, the code works fine. To take reflection out of the creation part:

import java.lang.reflect.Array;

class Test {
    public static void main(String[] args) throws Exception {
        int[] array1 = new int[10];
        Array.setInt(array1, 1, 100); // Works fine

        int[][] array2 = new int[10][10];
        Array.setInt(array2, 1, 100); // Throws IllegalArgumentException
    }
}
2
  • Thanks. But if the array is a multi-dimensional one instead of a one-dimensional array, is there anyway I can use Array.setInt to set the value of it? Commented Jul 14, 2013 at 21:08
  • @rolandluo: Your question makes no sense - you can only set an element of an integer array to an integer. Think about what you'd do without reflection first, then you'll see what I mean. You'll need to specify one index for each dimension, basically - with get calls for all but the last, and then a setInt call for the last one. Commented Jul 14, 2013 at 21:11

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.