Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The "pattern" (idiom) of passing an instance of <code>Class&lt;T&gt;</code> (typically to the constructor) is using <a href="http://docs.oracle.com/javase/tutorial/extra/generics/literals.html" rel="noreferrer">Class Literals as Runtime-Type Tokens</a>, and is used to keep a runtime reference to the generic type, which is otherwise erased.</p> <p>The solution is firstly to change the token class bound to:</p> <pre><code>Class&lt;? extends T&gt; </code></pre> <p>and then to put a similar requirement on your generic subclass as you did with your super class; have the concrete class pass a type token, but you can type it properly as a parameter:</p> <p>These classes compile without casts or warnings:</p> <pre><code>public abstract class Abstract&lt;T extends Abstract&lt;T&gt;&gt; { private final Class&lt;? extends T&gt; subClass; protected Abstract(Class&lt;? extends T&gt; subClass) { this.subClass = subClass; } } public class NonGeneric extends Abstract&lt;NonGeneric&gt; { public NonGeneric() { super(NonGeneric.class); } } public class Generic&lt;T&gt; extends Abstract&lt;Generic&lt;T&gt;&gt; { public Generic(Class&lt;? extends Generic&lt;T&gt;&gt; clazz) { super(clazz); } } </code></pre> <p>And finally at the concrete class, if you declare the usage as its own class, it doesn't require a cast anywhere:</p> <pre><code>public class IntegerGeneric extends Generic&lt;Integer&gt; { public IntegerGeneric() { super(IntegerGeneric.class); } } </code></pre> <hr> <p>I haven't figured out how to create an instance of <code>Generic</code> (anonymous or not) without a cast:</p> <pre><code>// can someone fill in the parameters without a cast? new Generic&lt;Integer&gt;(???); // typed direct instance new Generic&lt;Integer&gt;(???) { }; // anonymous </code></pre> <p>I don't think it's possible, but I welcome being shown otherwise.</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