Note that there are some explanatory texts on larger screens.

plurals
  1. POJava generics type erasure: when and what happens?
    text
    copied!<p>I read about Java's type erasure <a href="https://docs.oracle.com/javase/tutorial/java/generics/erasure.html" rel="nofollow noreferrer">on Oracle's website</a>.</p> <p><strong>When does type erasure occur?</strong> At compile time or runtime? When the class is loaded? When the class is instantiated?</p> <p>A lot of sites (including the official tutorial mentioned above) say type erasure occurs at compile time. If the type information is completely removed at compile time, how does the JDK check type compatibility when a method using generics is invoked with no type information or wrong type information?</p> <p>Consider the following example: Say class <code>A</code> has a method, <code>empty(Box&lt;?&nbsp;extends&nbsp;Number&gt;&nbsp;b)</code>. We compile <code>A.java</code> and get the class file <code>A.class</code>.</p> <pre><code>public class A { public static void empty(Box&lt;? extends Number&gt; b) {} } </code></pre> <pre><code>public class Box&lt;T&gt; {} </code></pre> <p>Now we create another class <code>B</code> which invokes the method <code>empty</code> with a non-parameterized argument (raw type): <code>empty(new Box())</code>. If we compile <code>B.java</code> with <code>A.class</code> in the classpath, javac is smart enough to raise a warning. So <code>A.class</code> <em>has</em> some type information stored in it.</p> <pre><code>public class B { public static void invoke() { // java: unchecked method invocation: // method empty in class A is applied to given types // required: Box&lt;? extends java.lang.Number&gt; // found: Box // java: unchecked conversion // required: Box&lt;? extends java.lang.Number&gt; // found: Box A.empty(new Box()); } } </code></pre> <p>My guess would be that type erasure occurs when the class is loaded, but it is just a guess. So when does it happen? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload