In Java, can an anonymous class declare its own type parameters?
Can an anonymous class declare its own type param开发者_高级运维eters?
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.
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
But, there is a way to use parameters.
Any declared method inside the anonymous class can use the
- properties of the outer class final
- method parameters and final method
- variables
the following code demonstrate it
public class Foo
{
private String value = "Hello ";
public void anonymousTest(final boolean asc)
{
final String world = "world";
new Comparable<String>()
{
@Override
public int compareTo(String o)
{
System.out.println( value + world);
int cmp = value.compareTo(o);
return asc ?cmp :0-cmp;
}
};
}
}
I hope that the example will help.
精彩评论