Java array narrow casting rules

casting, java, reflection

Solution

Object[] objArr = {"a","b","c"};
String[] strArr = (String[])objArr;

With that the problem is `{"a","b","c"}` which is an array of `Object`s not `String`s.

It's like doing something as follows -

Object obj = new Object();
String str = (String) obj; //ClassCastException

No exception with the following -

Object[] objArr = new String[] {"a","b","c"}; //Which is the case when you are using reflection
String[] strArr = (String[])objArr; //No exception

And it's like doing something as follows -

Object obj = new String();
String str = (String) obj;

Problem

According to JLS 7, 5.1.6 Narrowing Reference Conversion • From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a narrowing reference conversion from SC to TC. ``` Object[] objArr = {"a","b","c"}; String[] strArr = (String[])objArr; // ClassCastException ``` in the above example, both objArr and strArr are reference types and there's a narrow reference conversion from Object to String. ``` Object obj = "a"; String str = (String)obj; ``` but the following codes works fine: ``` Object[] objArr = (Object[])java.lang.reflect.Array.newInstance(String.class, 3); String[] strArr = (String[])objArr; ``` I want to ask the rules java uses to do the casting. As far as I can tell the differences between the two examples is that, in the first one, objArr is an Object array with component of type Object. the second is an Object array with component of type String. Please note that, I am not asking HOW to do the conversion, don't show me how to do this using Arrays.copyOf or other libraries.

Original source