Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassCastException when upgrading from Java6 to Java7 due to missing GenericArrayType

My code runs in Java 5 and 6, but when I upgraded to Java 7 I get a "java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.GenericArrayType".

For the following code:

public class A<T> {
  public Vector<Integer[]> arr;
}

System.out.println(((ParameterizedType)A.class.getField("arr").getGenericType()).getActualTypeArguments()[0]);
System.out.println(((ParameterizedType) A.class.getField("arr").getGenericType()).getActualTypeArguments()[0].getClass());

Java6 prints:

java.lang.Integer[]
class sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl

Java7 prints:

class [Ljava.lang.Integer;
class java.lang.Class

This different behavior is breaking my code which relies on generics. Can someone please help me understand why this happens and how to get GenericArrayType from Vector<Integer[]> arr?

like image 510
Ravi M Avatar asked Jul 27 '12 13:07

Ravi M


1 Answers

The documentation for GenericArrayType states it represents an array type whose component type is either a parameterized type or a type variable.

In the given example the array type is Integer[]. The component type, Integer, is neither a parameterized type nor a type variable. So your array type really should never have been represented by a GenericArrayType.

So apparently JRE6 behavior was buggy and it got fixed. Sorry. :(

like image 139
Ben Schulz Avatar answered Sep 22 '22 08:09

Ben Schulz