Java Generics - 9. Type Erasure

This is part 9 of the 9 part series on Java Generics 



Prev Topic

Topics







Java Generics - Type Erasure


Java Generics were created for tight type checking during compile time. Java complier applies the type erasure to the java code. Actually it replaces generic types by:
  •         Bounds for bounded types and Object for all unbounded types
  •         Inserts casting where necessary
  •         Add bridge methods whenever needed
The Generics also ensures that no new classes are created by the compiler to achieve these goals.
Have a look at the types class called Gen<E> below that is unbounded. It is in fact compiled as the class Gen with the unbounded type E replaced by the class Object.


       // Generic class
       class Gen<E> {
      
              private E val;
      
              public void setVal(E val) {
                     this.val = val;
              }
      
              public E getVal(){
                     return val;
              }     
       }
                    
       // The above clas gets compiles as
       class Gen {
      
              private Object val;
      
              public void setVal(Object val) {
                     this.val = val;
              }
      
              public Object getVal(){
                     return val;
              }     
       }


For a bounded type it actually gets replaced by the bound.


       // Generic class
       class Gen<E extends Number> {
      
              private E val;
      
              public void setVal(E val) {
                     this.val = val;
              }
      
              public E getVal(){
                     return val;
              }     
       }
                    
       // The above clas gets compiles as
       class Gen {
      
              private Number val;
      
              public void setVal(Number val) {
                     this.val = val;
              }
      
              public Number getVal(){
                     return val;
              }     
       }


The Java compiler also erases the type parameters in the method arguments that are generic as in the code below. This is why you will get the exception “Erasure of method foo(Object, Number) is the same as another method in type ErasureMethods” when you use both of the methods below in the same class. You cannot have two methods in a class that have same signature after type erasure.


       // Generic methods
       public <E, N extends Number> void foo(E e, N n) {
              /* */
       }
      
       // resolved as
       public void foo(Object e, Number n) {
              /* */
       }









Prev Topic

Topics





Comments

Popular posts from this blog

Java Generics - 7. Upper and Lower Bounds

Java Functional Programming : 3. The java.util.function Library

Java Generics - 3. Multiple bounding