Command Palette

Search for a command to run...

Back to the lesson: Topic 15.1 — Annotations
Core Java · Example 1 of 3 Java 8+

A custom annotation read at runtime

This is a web framework's router in miniature: find annotated methods, read their elements, call them.

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.

01

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.

02

Write an @Command("name") annotation and dispatch the string "greet" to the method annotated @Command("greet") in a Commands class.

03

Write a @Slow marker annotation and print how many of a class's methods carry it.

Explain it without notes

01

What are the three retention policies, and when would you use each?

02

How does a framework like JUnit or Spring use annotations?

03

What types are allowed for annotation elements, and why can't a default be null?

04

What is an annotation processor and what can it not do?

A custom annotation read at runtime Java 8+
Sign in to run this example in your browser.

Expected output

POST /users -> create() returns user created
helper: no @Route, skipped
GET /users -> list() returns all users