Retention decides who can see an annotation
An annotation is a label such as @Override or @Test that you attach to a class, method, field or parameter. It doesn't change what the code does by itself; the compiler, an annotation processor or a framework reads it (at compile time or, with RUNTIME retention, through reflection) and acts on it.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a @Max(int value) annotation for fields, and a method validate(Object o) that uses reflection to print every field whose int value is greater than its @Max.
Write an @Command("name") annotation and dispatch the string "greet" to the method annotated @Command("greet") in a Commands class.
Write a @Slow marker annotation and print how many of a class's methods carry it.
Explain it without notes
What are the three retention policies, and when would you use each?
How does a framework like JUnit or Spring use annotations?
What types are allowed for annotation elements, and why can't a default be null?
What is an annotation processor and what can it not do?
Expected output
@SourceOnly at runtime: false
@InClassFile at runtime: false
@AtRuntime at runtime: true
annotations reflection sees: 1