For some reason I don't understand why this code prints true
and false
, what is special about array that it does not include that annotation here?
It works as expected if you use getParameters
instead.
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.PARAMETER})
@interface Lel {
}
class Test {
public static void a(@Lel String args) {}
public static void b(@Lel String[] args) {}
public static void main(String[] args) throws Exception {
System.out.println(Test.class.getDeclaredMethod("a", String.class)
.getAnnotatedParameterTypes()[0].isAnnotationPresent(Lel.class));
System.out.println(Test.class.getDeclaredMethod("b", String[].class)
.getAnnotatedParameterTypes()[0].isAnnotationPresent(Lel.class));
}
}
In the annotated type @Lel String[]
, the annotation applies to the element type String
. To annotate the array type, you would use String @Lel []
.
The JLS contains some examples like this in §9.7.4:
Type annotations can apply to an array type or any component type thereof (§10.1). For example, assuming that
A
,B
, andC
are annotation types meta-annotated with@Target(ElementType.TYPE_USE)
, then given the field declaration:@C int @A [] @B [] f;
@A
applies to the array typeint[][]
,@B
applies to its component typeint[]
, and@C
applies to the element typeint
. For more examples, see §10.2.An important property of this syntax is that, in two declarations that differ only in the number of array levels, the annotations to the left of the type refer to the same type. For example,
@C
applies to the typeint
in all of the following declarations:@C int f; @C int[] f; @C int[][] f;
Also, getParameters()
will work to retrieve the annotation(s) if the way that your annotation is declared allows it to target the parameter declaration itself, as well as the type. JLS §9.7.4 explains in more detail the conditions under which an annotation is determined to target a type, declaration or both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With