Type Erasure


Edit the material here!

What happens when your Java generics code compiles

#This is a brief summary of type erasure that takes references from Javadocs, https://docs.oracle.com/javase/tutorial/java/generics/erasure.html as well as lectures provided in the module.

When Java compiler compiles your code into bytecode, it has to convert the parameterised types into an appropriate type.

  • Unbounded Parameterised Types are converted into Object type
  • Bounded Parameterised Types are converted into its bounds

Here's some example of code:

class Example<T> {
private T details;

Example(T details) {
this.details = details;
}
public void giveClarity(T furtherDetails) {
this.details = furtherDetails;
}
}

class BetterExample extends Example<String> {

BetterExample(String details) { super(details); }

public void giveClarity(String furtherDetails) { this.details = furtherDetails; }

}

In this case, when compiling, all the type parameter T in class Example is converted to Object type.

But lets consider something more... After compiling, the giveClarity method takes in an Object in class Example and a String in class BetterExample. And hence overriding is not explicitly taking place due to the difference in method signatures. Hence, Java compiler creates a bridge method to serve the purpose of overriding and polymorphism.

class BetterExample extends Example<String> {

BetterExample(String details) { super(details); }

// Bridge Method generated by Java Compiler
public void giveClarity(Object furtherDetails) { giveClarity( (String) furtherDetails); }

public void giveClarity(String furtherDetails) { this.details = furtherDetails; }

}

And this is what happens after we write a piece of code that involves the use of generics. :smiley