Friday, 8 July 2016

Problems with Generics (type erasure)

Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure.

Because of type erasure, type parameters cannot be determined at run-time.
Example, when an ArrayList is examined at runtime, there is no general way to determine whether, before type erasure, it was an ArrayList<Integer> or an ArrayList<Float>.

ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<Float> floatList = new ArrayList<Float>();
if (intList.getClass() == floatList.getClass()) { // evaluates to true

A generic class cannot extend the Throwable class in any way, directly or indirectly:
public class GenericException<T> extends Exception

The reason why this is not supported is due to type erasure:
try {
    throw new GenericException<Integer>();
} catch(GenericException<Integer> e) {
} catch(GenericException<String> e) {

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...