How Generic and Type Erasure work in Java
GenericsÂ
Generics are the most important part of java. With the use of generics, you can write generic classes, interfaces, and methods that perform operations on different types of data. The actual type on which they perform the operation is given by parameter. Before the generics, you can write classes, interfaces, and methods which operate on different types of data. But these codes are not type-safe you can explicitly cast these codes into appropriate types if you do a mistake to cast properly then an error occurred. Generics come with type safety. You do not need to worry about the casting in generics. It is implicitly happened by the compiler. Let’s learn the concept of generics and implicit casting with the help of code.
Example
Parameterized Type
The T in angle bracket (<>) is known as parameterized type. Most people think that when they declare a variable of generic code and pass argument in angle bracket suppose Gen a = new Gen, they think a new Gen class is created. But this is not happening actually, Java uses the type erasure mechanism for generics. So, let’s learn type erasure and see what happen behind the scene.
Type Erasure
Actually, when we compile the Gen class the type erasure removed all the parameterized types. The type erasure replaces the parameterized type with the bound. If no bound is specified then the type erasure replaces the parameterized type with the Object. So, after compiling the Gen class. It looks like this;
Actually, when we declare the variable of Gen, suppose we declare Gen iob = new Gen and Gen strob = new Gen both the object is an instance of Gen. But what happens when we call the getob function actually we get the value in the type of Integer if we call this function through iob and the value in the type of String when we call this function through strob. But this function is returning Object in code. So it means down-casting is happening behind the scene. How this happens let’s come and see this through an example:
Example
Output:
So, you see the output v is â88â and str is âDummy Stringâ. But the question arises of how down-casting is performed implicitly because we know down-casting is an explicit process. Actually, in generics, it performs implicitly. The reason behind that when you compile the GenDemo class the compiler appends the code for downcasting in that. The GenDemo class after compile look like that:
See on line number 10 and 18. The compiler ensures the proper down-casting in generic that why generic is type safe. Most people do not know about that but it happens behind the scene.
I hope this material is helpful for you in writing generic code properly. And now I think you guys are clear about the concept and know what happened behind the scene with generics.
 Thank you for being with me in this article.
Farhan Bajwa – is a Principal software engineer at Pioneer Logics.