Java’s Type Erasure + Compiler black magic = Bridge methods

This time we will look at an extreme consequence of Java’s Type Erasure. This example shows what can happen to the semantics of Java language by Type Erasure without some compiler massage. Unlike other articles, It makes more sense to explain the behavior along side of the code. So I keep the abstract of the article simple. Below we have a class called Number<T> which has a protected field number of type T and with methods setNumber(T) and T getNumber(). Based on this class, I have created a new subclass called NumberString which extends from Number<String> and provides a method setNumber(String).

Now the comments in the code explain what could happen to a simple call such as number.setNumber(“10”); when number is a super class reference and without some compiler tricks.

Leave a comment

Leave a Reply