Type Erasure in Java

Prerequisite : Generics
Generics concept is introduced in Java language to provide tighter type checks at compile time and to support generic programming. The way to implement generics, the Java compiler applies type erasure to:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

In general, the compiled generic code actually just uses java.lang.Object wherever you talk about T (or some other type parameter) – and there’s some metadata to tell the compiler that it really is a generic type. When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for T is) and verifies at compile time that you’re doing the right thing, but the emitted code again just talks in terms of java.lang.Object – the compiler generates extra casts where necessary. At execution time, a List and a List are exactly the same; the extra type information has been erased by the compiler.

How Type Erasure works according to the Program?



filter_none

edit
close

play_arrow

link
brightness_4
code

// Here, T is bounded by Object i.e. java.lang.Object
class GFG<T> {
// Here, T will be replaced by default i.e. Object
    T obj; 
  
    GFG(T o)
    {
        obj = o;
    }
    T getob()
    {
        return obj;
    }
}

chevron_right


After compilation, the code is replaced by default Object like the below:

class GFG
{
// Here, T will be replaced by default i.e. Object
    Object obj;
    GFG(Object o)
    {
        obj=o;
    }
    Object getob()
    {
        return obj;
    }
}
filter_none

edit
close

play_arrow

link
brightness_4
code

// Here, T is bounded by Object i.e. java.lang.Object
class Geeks<T extends String> {
  
 // Here, T will be replaced by String i.e. java.lang.String
    T str;
    Geeks(T o)
    {
        str = o;
    }
    T getob()
    {
        return str;
    }
}

chevron_right


After compilation, the code is replaced by String like the below:

class Geeks
{

//Here, T will be replaced by String i.e. java.lang.String
    String str;

    Geeks(String o)
    {
        str=o;
    }
    String getob()
    {
        return str;
    }
}

NOTE: After the compilation of above two classes, we can check the contents of both the classes. After the compilation, in GFG class T will be replaced by Object and in Geeks class T will be replaced by String. We can check the content by running the compiled code by javap className command.

TypeErasure Implementation

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate
// concept of TypeErasure
  
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericsErasure {
    public static void main(String args[])
    {
        List<String> list = new ArrayList<String>();
        list.add("Hello");
        Iterator<String> iter = list.iterator();
        while (iter.hasNext()) {
            String s = iter.next();
            System.out.println(s);
        }
    }
}

chevron_right


Explanation: Here when we compile the code, it does not throw any warning message to the console screen because here we are using Type Erasure.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate
// concept of TypeErasure
import java.io.PrintStream;
import java.util.*;
  
public class GenericsErasure {
  
    public GenericsErasure()
    {
    }
  
    public static void main(String args[])
    {
        List list = new ArrayList();
        list.add("Hello");
        String s;
        for (Iterator iter = list.iterator(); iter.hasNext();
             System.out.println(s))
            s = (String)iter.next();
    }
}

chevron_right


Explanation: Here when we compile the code we will get some note from the compiler i.e. GenericsErasure.java uses unchecked or unsafe operations.

Reference:
Type Erasure
StackOverFlow



My Personal Notes arrow_drop_up

Hello everyone, I am Bishal KUMAR Dubey and most importantly an idea creator I just love Programming languages and love to know new concepts everyday,every minute,every second Here to help Other GEEKS

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.