Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, can an anonymous class declare its own type parameters?

Can an anonymous class declare its own type parameters?

like image 481
John Assymptoth Avatar asked Jan 23 '11 15:01

John Assymptoth


2 Answers

You are right, it's not possible. Since an anonymous class is meant to be used only once, what would be the point of adding type parameters to it which you can never actually use/inherit? You can't instantiate an anonymous class more than once from any other code location than the one which defines it, and you can't subclass it either.

like image 171
Péter Török Avatar answered Oct 21 '22 21:10

Péter Török


No. The Java Language Specification exhaustively defines the possible arguments to a class instance creation expression as follows:

A class instance creation expression specifies a class to be instantiated, possibly followed by type arguments (if the class being instantiated is generic (§8.1.2)), followed by (a possibly empty) list of actual value arguments to the constructor. It is also possible to pass explicit type arguments to the constructor itself (if it is a generic constructor (§8.8.4)). The type arguments to the constructor immediately follow the keyword new. It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments (§4.5.1). Class instance creation expressions have two forms:

  • Unqualified class instance creation expressions begin with the keyword new. An unqualified class instance creation expression may be used to create an instance of a class, regardless of whether the class is a top-level (§7.6), member (§8.5, §9.5), local (§14.3) or anonymous class (§15.9.5).

  • Qualified class instance creation expressions begin with a Primary. A qualified class instance creation expression enables the creation of instances of inner member classes and their anonymous subclasses.

So while you can specify the actual type parameters of the super class or interface, or the constructor, you can not define new ones. While I grant that this might be useful in some rare cases (because the new type parameter could be used from the class body), there are easy workaround for that:

  • wrap the class instance creation expression in a generic method (the anonymous class will see the enclosing method's type parameter)
  • use a named class
like image 21
meriton Avatar answered Oct 21 '22 23:10

meriton