Question
What are the differences between Field#getAnnotations() and Field#getDeclaredAnnotations() in Java?
import java.lang.reflect.Field; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface MyAnnotation { String value(); } class MyClass { @MyAnnotation("Test") private String myField; } public class Main { public static void main(String[] args) throws NoSuchFieldException { Field field = MyClass.class.getDeclaredField("myField"); System.out.println("Annotations: " + Arrays.toString(field.getAnnotations())); System.out.println("Declared Annotations: " + Arrays.toString(field.getDeclaredAnnotations())); } }
Answer
In Java, reflection API provides various ways to retrieve annotations. The methods Field#getAnnotations() and Field#getDeclaredAnnotations() serve two distinct purposes regarding how annotations are accessed at runtime.
// Example output from the code snippet above would be:
// Annotations: [interface MyAnnotation]
// Declared Annotations: [interface MyAnnotation]
Causes
- Field#getAnnotations() returns all annotations present on the field, including inherited annotations from superclasses.
- Field#getDeclaredAnnotations() only returns annotations that are declared directly on the field, excluding inherited annotations.
Solutions
- Use Field#getAnnotations() when you need to access both inherited and declared annotations on a field.
- Use Field#getDeclaredAnnotations() when you only want to interact with annotations that are explicitly declared on that particular field.
Common Mistakes
Mistake: Assuming Field#getAnnotations() and Field#getDeclaredAnnotations() produce the same result.
Solution: Remember that getAnnotations() accesses all annotations, including inherited ones, while getDeclaredAnnotations() only accesses those declared directly on the field.
Mistake: Neglecting to check if a field has annotations before invoking these methods.
Solution: Always ensure to check if the field has annotations by inspecting its declared annotations first to avoid unnecessary reflection calls.
Helpers
- Java reflection
- Field#getAnnotations()
- Field#getDeclaredAnnotations()
- Java annotations
- Java programming
- Difference between annotations