Hello,
To get the type annotations on a field you would have to use
field.getAnnotatedType().getAnnotations();
See
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/Field.html#getAnnotatedType()
Calling getAnnotations on a field returns the declaration annotations.
HTH,
-Joe
On 11/6/2018 10:48 AM, Kasper Nielsen wrote:
Hi,
I'm trying to understand exactly how ElementType.TYPE_USE should work.
I'm asking because the following program only prints that s has one 2
annotation.
I believe it should either print 3 or be flagged at compilation time.
public class TestClass {
@X
@Y
@Z
String s;
public static void main(String[] args) throws Exception {
System.out.println(TestClass.class.getDeclaredField("s").getAnnotations().length);
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface X {}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Y {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.TYPE_USE })
@interface Z {}
}
ElementType.TYPE_USE alone isn't enough for the annotation information to
be retained at runtime.
/Kasper