Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is kind of silly. It would have been better, for most use cases, if <code>x.getClass()</code> returns <code>Class&lt;? extends X&gt;</code>, instead of the erased <code>Class&lt;? extends |X|&gt;</code>.</p> <p>The erasure is the cause of loss of information, making your code, apparently safe, fail to compile. <code>t.getClass()</code> returns <code>Class&lt;? extends |T|&gt;</code>, and <code>|T| = Number</code>, so it returns <code>Class&lt;? extends Number&gt;</code>.</p> <p>The erasure (mandated by the language spec) is to maintain theoretical correctness. For example</p> <pre><code>List&lt;String&gt; x = ...; Class&lt;List&gt; c1 = x.getClass(); // ok Class&lt;List&lt;String&gt;&gt; c2 = x.getClass(); // error </code></pre> <p>Although c2 seems very reasonable, in Java, there is really no such class for <code>List&lt;String&gt;</code>. There is only the class for <code>List</code>. So allowing c2 would be, theoretically incorrect.</p> <p>This formality created lots of problem in real world usages, where programmers can reason that <code>Class&lt;? extends X&gt;</code> is safe for their purposes, but have to cope with the erased version.</p> <p>You can simply define your own <code>getClass</code> that returns the un-erased type</p> <pre><code>static public &lt;X&gt; Class&lt;? extends X&gt; getFullClass(X x) return (Class&lt;? extends X&gt;)(Class) x.getClass() ; &lt;T extends Number&gt; void foo(T t) { Class&lt;? extends T&gt; klass = getFullClass(t); } </code></pre>
 

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