What is erasure?

Generics was added in java later. The way that generics was added to java was the need for compatibility with previous version of java. Thus any changes to the syntax of the java language or to the JVM had to avoid older code. The way java implements generics while satisfying this constraints is through the use of erasure.
When the java code is compiled all generic type information was removed(erased). This means replacing type parameters with their bound type, which is object if no explicit bound is specified, and then applying the appropriate casts(as determined by type arguments) to maintain type compatibility with the types specified by the type arguments. The compiler also enforces this type compatibility. This approach to generics means that no type parameters exist at run time. They are simply a source code mechanism.
Consider the following two classes:
class Gen
T ob;
Gen(T ob){this.ob=ob;}
T getob(){return ob;}
class Genstr
T str;
Genstr(T str){this.str=str;}
T getstr(){return str;}
After these two classes are compiled, the T in Gen will be replaced by Object.
The T in Genstr will be replaced by String.
You can conform this by running javap on their compiled classes.
The results are
Class Gen extends java.lang.Object{
Java.lang.Object ob;
Java.lang.Object getob();
Class Genstr extends java.lang.Object{
Java.lang.String str;
Java.lang.String getstr();
Withen the code for Gen and Genstr, casts are employed to ensure the proper typing.
For example
Gen i=new Gen(10);
Int x=i.getob();
Will be
Gen i=new Gen(10);
Int x=(Integer)i.getob();

No comments:

Post a Comment