Troskyvs
Troskyvs

Reputation: 8077

java Array.newInstance throws ClassCastException, why?

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?

Upvotes: 0

Views: 201

Answers (1)

Eran
Eran

Reputation: 393986

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);

Upvotes: 5

Related Questions