Diamond with anonymous classes: what if anonymous class were generic

Srikanth srikanth.adayapalam at oracle.com
Tue Jun 23 08:51:53 UTC 2015

On Thursday 11 June 2015 08:02 PM, Georgiy Rakov wrote:
> Hello,
> currently when diamond is used in anonymous class instance creation 
> expression the class being instantiated is not generic. I believe this 
> is the reason why there are exceptions specified in the assertion below:
>     ***It is a compile-time error if the superclass or superinterface
>     type of the anonymous class, T, or any subexpression of T, has one
>     of the following forms:
>     - A type variable (4.4) that was not declared as a type parameter
>     (such as a type variable produced by capture conversion (5.1.10))
>     - An intersection type (4.9)
>     - A class or interface type, where the class or interface
>     declaration is not accessible from the class or interface in which
>     the expression appears.***
>     The term "subexpression" includes type arguments of parameterized
>     types (4.5), bounds of wildcards (4.5.1), and element types of
>     array types (10.1). It excludes bounds of type variables.***
> What if the anonymous class declaration derived the type parameters 
> from the type specified in the instance creation expression (from 
> super type). In this case the anonymous class would be a generic class 
> and the type of the instance created will be a regular 
> parameterization of that generic class. In this case I believe the 
> situation will be identical to ordinary non-anonymous classes and 
> there would be no needs to specify inferred types in the class signature.

I am not sure I entirely understand what you are saying here - There is 
no notion of an anonymous class declaration "deriving" its type 
parameters from its super type. Neither the compiler nor the JLS view 
the anonymous
class as being generic and "type of the instance created will be a 
regular parameterization of that generic class".

Do you have in mind some code that you think should not be compiled, 
but  is or should be but is not ?

Is that what the code snippet below is supposed be ???

class Foo<T> {

Foo<String> inst = new Foo<>(){};

In this case, the anonymous type's super type is Foo<String> and I don't 
see an issue here.


> For instance:
>     class Foo<T> {ge
>     }
>     Foo<String> inst = new Foo<>(){};
> Here anonymous class would have type parameter T derived from its 
> super type T. The type of instance creation expression will be the 
> parameterization of this generic anonymous class with T inferred as 
> String.
> I wonder if you considered such option.
> Thank you,
> Georgiy.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20150623/42d6e39c/attachment-0001.html>

More information about the compiler-dev mailing list