Skip to content

Chapter 34 of 37

Annotations

Declare metadata, control retention and targets, and process it at compile time or runtime.

36 minutes 10 quick checksBy Subha Prasad
Lesson 34 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Annotations attach metadata to declarations and type uses. Meta-annotations control where metadata is legal and how long it remains.

A runtime annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Audited {
    String action();
}

@Audited(action = "user.read")
public User find(long id) { return repository.find(id); }

SOURCE annotations support tooling, CLASS annotations remain in bytecode, and RUNTIME annotations are reflectively visible. Repeatable and inherited annotations have specific rules. Compile-time processors can validate models and generate sources without runtime reflection. Treat annotations as declarative metadata, not hidden control flow that makes behavior impossible to trace.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes annotation?
Which Java term matches this description: Structured metadata attached to program elements.
Which statement best describes Retention?
Which Java term matches this description: A meta-annotation selecting source, class-file, or runtime lifetime.
Which statement best describes Target?
Which Java term matches this description: A meta-annotation restricting allowed declaration contexts.
Which statement best describes Override?
Which Java term matches this description: A compiler-checked marker that a method overrides a supertype method.
Which statement best describes annotation processor?
Which Java term matches this description: A compile-time tool that reads annotations and may generate sources.

0 of 10 checks passed

Your progress is saved on this device.

Annotations | Java Lesson | Subha Prasad