Course contentsShow
← Java
Lesson 2430 of 2,87046. AnnotationsFree lesson

Nested Annotations as Element Types

Use other annotations as element types to create complex, structured metadata.

Nested Annotations as Element Types

You'll learn: How to use other custom annotations as element types to build structured, hierarchical metadata that captures complex relationships.

The Core Idea

Just as objects can contain other objects, annotations can contain other annotations. When you define an annotation element, you can specify another annotation type as its value type. This lets you nest annotations inside annotations, creating rich, multi-level metadata structures.

Think of it like a form with sub-forms: a job application might have a main form plus a nested "education history" section with its own fields. Similarly, a main annotation can contain nested annotations with their own elements.

Why Nest Annotations?

Sometimes a single flat list of elements isn't enough. You might need to group related metadata together or represent hierarchical information. For example, configuring a database entity might require nested annotations for table details, column mappings, and relationship constraints—all organized logically.

The Syntax

Since you've already created custom annotations with various element types, adding nested annotations follows the same pattern—just use an annotation type where you'd normally use a primitive or String:

@interface Address {
    String street();
    String city();
}

@interface Author {
    String name();
    Address address();  // Nested annotation element
}

@Author(
    name = "Jane Doe",
    address = @Address(street = "123 Main St", city = "Springfield")
)
class Book { }

Notice how @Address is instantiated inline using the @ symbol within the @Author annotation.

Key Takeaway: Nested annotations let you compose complex, structured metadata by using custom annotation types as element values, enabling hierarchical and organized configuration directly in your code.