0

Very simple code:

    int[] a = new int[]{4,1,2,3};
    Array a3 = (Array) Array.newInstance(a.getClass(), a.length);

It throws an exception 'Exception in thread "main" java.lang.ClassCastException: [[I cannot be cast to java.lang.reflect.Array'

Where did I get wrong and how to fix it?

1
  • Are you trying to create a new int[] array or a new int[][] array? Commented Nov 20, 2018 at 11:08

1 Answer 1

5

Array.newInstance(a.getClass(), a.length) creates a two dimensional int array (that's what happens when you create an array whose element type is an int[]), so it should be:

int[][] a3 = (int[][]) Array.newInstance(a.getClass(), a.length);

Array is a class used to create array instances with reflection, but array instances are not instances of that class.

BTW, if you intended to create a one dimensional int array (i.e. int[]), you should write:

int[] a3 = (int[]) Array.newInstance(int.class, a.length);
Sign up to request clarification or add additional context in comments.

Comments

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.