Home > Uncategorized > Effect of Type Erasure on Casts

Effect of Type Erasure on Casts

As put in the previous blog, runtime type erasures for java generics offer both advantages and annoyances.  Lets try exploring its effect on runtime type casting.

Assume we have a code snippet with explicit typecasts and implicit assumptions

private void callMethod(Object array)
{ List<Integer> copiedArray = (List<Integer>)array;
System.out.println(”First Element ->”+copiedArray.get(0));
}

private void callMethod(Object array)
{    List<Integer> copiedArray = (List<Integer>)array;
     System.out.println("First Element ->"+copiedArray.get(0));
}

private void callingMethod()
{  List<String> stringArray = new ArrayList<String>(2);
   stringArray.add(new String("hello"));
   callMethod(stringArray);
}

The class containing these method would compile and run without complaints.  Reason: During compile time, compiler cannot detect the linked caller and callee parameter types, and during runtime, 'runtime type erasures' ensure the type of a casted object is not maintained in the constant pool.  Let us slightly modify the calling method as below.
private void callMethod(Object array)
{    List<Integer> copiedArray = (List<Integer>)array;
     System.out.println("First Element ->"+copiedArray.get(0).getClass()); // call a method on the fetched object
}
This would throw ClassCastException during the runtime, as the actual type checking by the JVM is done then.

Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.