Sobes.tech
Middle

What is the purpose of type erasure in Java?

sobes.tech AI

Answer from AI

Type Erasure in Java exists to ensure backward compatibility with earlier versions of Java that did not have generics.

When Java code with generics is compiled, the compiler automatically removes all information about type parameters (e.g., <String> or <Integer>) from the bytecode. Instead, all instances of generic types are replaced with their upper bound (usually Object), and explicit type casts are inserted when necessary.

This allows code using generics to interact with libraries and classes compiled without generics support, without changing their bytecode.

Main consequences of type erasure:

  • Impossible to obtain information about type parameters at runtime: Using .getClass().getGenericSuperclass() or similar methods to get specific type parameters will not work for regular instances.
  • Impossible to create arrays of parameterized types: new ArrayList<String>[10] will cause a compile-time error.
  • Impossible to use parameterized types in instanceof: object instanceof List<String> will cause a compile-time error. You can use object instanceof List.

Example of type erasure:

// Before erasure
List<String> strings = new ArrayList<>();
strings.add("Hello");
String s = strings.get(0);

// After erasure in bytecode (approximately)
List strings = new ArrayList(); // List<String> is erased to List
strings.add("Hello"); // Despite erasure, the compiler checks the type when adding
String s = (String) strings.get(0); // Explicit cast is added

Thus, type erasure is a compromise between adding powerful features (generics) and maintaining backward compatibility with existing code base.