Summary
Annotations applied to a constructor of a class C
are not propagated to the corresponding constructor of an anonymous subclass of C
. There are other cases in which annotations are automatically propagated like annotations in a record component which are propagated to several implicitly declared elements in a record class, in particular to its canonical constructor if it is not explicitly declared.
Problem
Annotations applied to the constructor of a given class are not propagated to the corresponding constructor of an anonymous subclass. For example for code like:
@Target(value = {ElementType.PARAMETER})
@interface ParamAnnotation {}
@Target(value = {ElementType.CONSTRUCTOR})
@interface CtrAnnotation {}
@Target({ElementType.TYPE_USE})
@interface TypeAnno {}
@Target({ElementType.TYPE_PARAMETER})
@interface TypeAnnoForTypeParams {}
class Test {
@CtrAnnotation
@TypeAnno
<@TypeAnnoForTypeParams T> Test(String firstParam,
@TypeAnno String secondParam,
@ParamAnnotation String thirdParam) {}
public void m() {
// let's create an anonymous class
new Test("", "", "") {};
}
}
none of the annotations applied to the constructor of class Test
is propagated to the constructor of any anonymous subclass of it. Given that it is not possible to explicitly declare the constructor of an anonymous class, not propagating the annotations to the corresponding constructor in the anonymous subclass implies a hard limitation for which there is no possible workaround.
Solution
The proposed solution is to propagate annotations applied to the constructor of a class C
to the corresponding constructor of any anonymous subclass of C
. This implies propagating declaration annotations applied to the constructor per se, declaration annotations applied to its parameters and type annotations applied to any type or type parameter.
Specification
The JLS doesn't mandate annotations applied to a constructor to be propagated to the corresponding constructor of an anonymous subclass but we are already propagating annotations in records in very similar cases. Not propagating annotations to anonymous class constructors seems inconsistent. Consider that we are currently propagating the parameter names to the anonymous class constructor, not propagating the annotations seems inconsistent and forces users to have more than one source of truth when looking for information. Also it should be considered that it impossible to explicitly apply annotations to the constructor of an anonymous class given that these constructors can't be explicitly declared.
- csr of
-
JDK-8274617 annotations in the super class constructor are not propagated to the anonymous class constructor
- Closed