Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy isn't the enclosing class included in the generic parameters for inner class constructors?
    text
    copied!<p>Check it out.</p> <pre><code>import java.lang.reflect.*; import java.util.Arrays; class Test { class Inner { public &lt;T&gt; Inner(T arg) { } } public static void main(String[ ] args) { Constructor&lt;?&gt; constructor = Test.Inner.class.getConstructors( )[0]; System.out.println ( "Regular parameters: " + Arrays.toString(constructor.getParameterTypes( )) + "\nGeneric parameters: " + Arrays.toString(constructor.getGenericParameterTypes( )) ); } } </code></pre> <p>Running this prints the following.</p> <blockquote> <p>Regular parameters: [class Test, class java.lang.Object]<br> Generic parameters: [T]</p> </blockquote> <p>My understanding of Java inner classes (i.e. non-static) is that their constructors implicitly have a parameter for their enclosing class. So, to get an instance of <code>Inner</code>, you call its constructor like so.</p> <pre><code>Test.Inner foo = new Test( ).new Inner(new Object( )); </code></pre> <p>And what actually happens is that the instance of <code>Test</code> is passed to the constructor for <code>Inner</code> (along with any other arguments), where it's assigned to an implicit instance field.</p> <p>Examining the nullary constructor for <code>Inner</code> bears this out, as calling <code>getParameterTypes</code> returns an array containing the <code>Class</code> objects representing <code>Test</code> and <code>Object</code> (the erasure of <code>T</code>).</p> <p>However, since the constructor is generic, calling <code>getGenericParameterTypes</code> instead returns an array containing only the type variable <code>T</code>. The implicit parameter for the enclosing class is missing.</p> <p>This only seems to happen when the inner class constructor declares a type variable. Why does it do that? Is it a bug?</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