Tuesday, September 4, 2012

Genarics vs it's byte code

Lets begin this discussion with some code samples

sample 1 class with out generics
sample 2 class with generics

As every one can see sample one class does not generalize its map but in sample two it is generalized.Now we compile both classes and we get two byte codes , Lets name them as byte code 1 and byte code 2 .

Are those two byte codes are same or not ?

If you look blindly you may answer that question with no , because every one can see that the content of two classes are different, so there can not be same byte code for both sample one and sample two classes . But truth is they are same.

How they are same and why it is same ?

Its better to know why it is same before we hands on how it is same . Simple answer for why it is same is , to ensure the backward compatibility of the code.Java introduce Generics with java 5 version , if we change infrastructure of java byte code with version 5 those code may not be compatible with previous versions . In simple your pre java 5 classes can not communicate with your java 5 object if their byte code infrastructure is different.

Now we can hands on how it is done.When java compile the source code it ensure the type safety by using generics after that compiler erase all the generics using eraser utility and then compile the source code now there is no generics in the byte code but code is type safe to more information on how this work go to follow this java documentation .