Course contentsShow
← Java
Lesson 2382 of 2,87045. Reflection APIFree lesson

Reading Annotations from Fields

Accessing annotations on fields via Field.getAnnotation() and Field.getDeclaredAnnotations() for field-level metadata.

Reading Annotations from Fields

What you'll learn: How to retrieve annotation metadata attached to class fields using Java's reflection API.

Just as you learned to read annotations from methods, Java fields can also carry annotations that provide metadata about those variables. Think of field annotations like price tags on store items—they're additional information attached to each field that your code can read and act upon at runtime.

Core Concept

When you annotate a field in Java (like @JsonProperty on a data field or @Autowired on a dependency), those annotations aren't just documentation—they're accessible metadata. The Field class provides two key methods for reading this information:

Field.getAnnotation(Class<T> annotationClass) - Returns a specific annotation if present on the field, or null if not found. This searches through the field's annotations for an exact match.

Field.getDeclaredAnnotations() - Returns an array of all annotations directly present on the field. This gives you complete visibility into every annotation attached to that field.

How It Works

First, obtain a Field object via reflection. Then call these methods to inspect its annotations. You can check for specific annotation types to drive behavior—like serialization frameworks reading @Column annotations to map fields to database columns, or validation frameworks checking @NotNull to enforce constraints.

The difference between these methods mirrors what you've seen elsewhere: getAnnotation() is targeted and type-safe, while getDeclaredAnnotations() gives you the complete picture when you need to scan all metadata.

Key Takeaway: Use Field.getAnnotation() to check for specific annotations on fields and Field.getDeclaredAnnotations() to retrieve all field-level annotations—essential for implementing metadata-driven features like serialization, validation, and dependency injection.