Generics & Type Erasure In Java

  • Post last modified:November 16, 2023
  • Reading time:3 mins read

Discussing Generics and Type erasure with simple code example

Introduction

  • Generics Introduced stronger compile time type check for developers. Since type check was added for compile time, it results in losing Type information at runtime. This is called type erasure.
  • In this article, we will learn about Type erasure along with examples.

Generics In Java

  • Generics were introduced in Java 5, its main goal was to provide compile-time type-safety checks along with flexibility and reusable code.
  • One area where Generics played a significant role was the Collection framework. Before Generics Java Collection was used with RAW type. Using Raw type was error-prone and developers often did casting of data type, resulting in type-casting exceptions.
  • With Generics, developers would define the data type they need to store into the collection and any violation would be a compile-time error.

Type Erasure

  • In Java type information in Generics is mainly available for compile time so that the compiler can check the type and throw errors during compilation.
    This information is removed at the runtime because all the data types are converted/cast to the Object class. This type of erasure.
  • Type erasure was a design choice that the Java designer made to make it backward-compatible.

Code Example

  • Let’s consider a simple example. We are creating GenericContainer which has a constructor and add method.
  • GenericContainer is taking Type parameter T, which is passed to this class from client code during initialization.
    `GenericContainer<String> gc = new GenericContainer<>();`
public class GenericContainer<T> {

    int initialCapacity = 100;
    Object[] elementArray = null;
    T t;

    public GenericContainer() {
        elementArray = new Object[initialCapacity];
    }

    public void add(T t){
        this.t = t;
       // add element
    }
}
  • If we compile this file we shall see that the type parameter is erased and the parent class Object has been used.
javac ./src/main/java/Generics/GenericContainer.java
// GenericContainer.class
  • Now we can use `javap` tool to inspect the GenericContainer.class file 
javap -c ./src/main/java/Generics/GenericContainer.class
  • As we can see putfield is passing Object type and doesn’t store generic parameters.

Conclusion

  • In this article, we discussed Generics and Type erasure. We also saw a simple code example to verify that.
  • That is all for this article, we will cover limitations that were introduced due to type erasure in future articles.

Before You Leave