An annotation is a label that starts with @ and adds information to code, such as @Override. Some annotations are read by the compiler to catch mistakes. Others are kept at run time, where a program can read them with reflection, Java’s ability to examine classes, fields and methods while running. Frameworks such as Spring, JUnit and Hibernate are built on this idea. This lesson shows the built-in annotations, then builds a small validator from a custom annotation.
In this lesson you will learn
- What
@Override,@FunctionalInterface,@Deprecatedand@SuppressWarningsdo - Declaring your own annotation with
@interface @Retentionand@Target- Reading annotations and field values with reflection
- Calling a method by name
You should know inheritance, interfaces and lambdas.
Built-in Annotations
import java.util.ArrayList;
import java.util.List;
public class Main {
static class Animal {
String sound() { return "..."; }
@Deprecated(since = "2.0")
String oldName() { return "animal"; }
}
static class Cat extends Animal {
@Override // compiler checks this really overrides a method
String sound() { return "Meow"; }
// @Override String sond() { ... } <- would be a compile error: nothing to override
}
@FunctionalInterface // compiler checks there is exactly one abstract method
interface Converter { double convert(double value); }
@SuppressWarnings({"unchecked", "rawtypes"}) // silence specific, understood warnings
static List<String> legacyList() {
List raw = new ArrayList();
raw.add("from old code");
return (List<String>) raw;
}
public static void main(String[] args) {
System.out.println(new Cat().sound());
Converter takaToUsd = t -> t / 122.0; // example exchange rate
System.out.printf("1000 taka is about %.2f USD%n", takaToUsd.convert(1000));
System.out.println(legacyList());
}
}
Output
Meow
1000 taka is about 8.20 USD
[from old code]
@Overrideasks the compiler to check that the method really overrides one in a parent class. A typo such assond()then becomes a compile error instead of a silent new method.@FunctionalInterfacemakes the compiler check that the interface has exactly one abstract method, so it can always be used with a lambda.@Deprecated(since = "2.0")marks code that should no longer be used. Any code that calls it gets a compiler warning.@SuppressWarningssilences specific warnings, here about the rawListtype in old-style code. Keep it as narrow as possible, on one method rather than a whole class.
A Custom Annotation and a Reflection-Based Validator
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
// A custom annotation, kept at run time so reflection can read it
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MaxLength { int value(); }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank { }
static class SignupForm {
@NotBlank @MaxLength(10) String username;
@NotBlank String email;
@MaxLength(11) String phone;
SignupForm(String u, String e, String p) { username = u; email = e; phone = p; }
}
// A tiny validator: it knows nothing about SignupForm, only the annotations
static int validate(Object obj) throws IllegalAccessException {
int problems = 0;
for (Field f : obj.getClass().getDeclaredFields()) {
Object value = f.get(obj);
String text = value == null ? "" : value.toString();
if (f.isAnnotationPresent(NotBlank.class) && text.isBlank()) {
System.out.println(" " + f.getName() + ": must not be blank");
problems++;
}
MaxLength max = f.getAnnotation(MaxLength.class);
if (max != null && text.length() > max.value()) {
System.out.println(" " + f.getName() + ": longer than " + max.value() + " characters");
problems++;
}
}
return problems;
}
public static void main(String[] args) throws Exception {
System.out.println("Checking a bad form:");
validate(new SignupForm("shahriar_hasan", " ", "017123456789"));
System.out.println("Checking a good form:");
int found = validate(new SignupForm("tania", "tania@example.com", "01712345678"));
System.out.println(" problems found: " + found);
// Reflection can also list methods and call them by name
Method m = String.class.getMethod("toUpperCase");
System.out.println("Called by name: " + m.invoke("reflection"));
}
}
Output
Checking a bad form:
username: longer than 10 characters
email: must not be blank
phone: longer than 11 characters
Checking a good form:
problems found: 0
Called by name: REFLECTION
@interface MaxLengthdeclares an annotation with one setting,value, so it can be written as@MaxLength(10).@NotBlankhas no settings at all.@Retention(RetentionPolicy.RUNTIME)keeps the annotation in the compiled class so reflection can see it. Without it, annotations are dropped before the program runs.@Target(ElementType.FIELD)allows the annotation only on fields; putting it on a method is a compile error.validateknows nothing about sign-up forms. It asks the object’s class for its fields (getDeclaredFields), reads each value withf.get(obj), and checks whatever annotations it finds. The same validator would work for any class.- Reflection can also look up methods by name and call them with
invoke, as the last line does withtoUpperCase.
Retention Policies
| Retention | Kept until | Used by |
|---|---|---|
SOURCE | Compilation only | Compiler checks such as @Override |
CLASS (default) | The .class file, but not loaded at run time | Build tools that read class files |
RUNTIME | While the program runs | Reflection, frameworks, validators |
Common Mistakes
- Forgetting
@Retention(RUNTIME), sogetAnnotationalways returns null. - Using reflection for ordinary code. It is slower, skips compile-time checks and breaks silently when names change. Use it for frameworks and tools, not everyday logic.
- Reading private fields of other classes. This needs
setAccessible(true), which can be blocked by the module system. - Relying on the order of
getDeclaredFields(). The Java documentation does not promise any particular order.
Practice Exercises
Exercise 1. Add a @Min(int value) annotation for numeric fields and check it in validate.
Show answer
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Min { int value(); }
// inside the loop in validate():
Min min = f.getAnnotation(Min.class);
if (min != null && value instanceof Integer n && n < min.value()) {
System.out.println(" " + f.getName() + ": must be at least " + min.value());
problems++;
}
Exercise 2. Use reflection to print the names of all public methods of String that start with “to”.
Show answer
Arrays.stream(String.class.getMethods())
.map(Method::getName)
.filter(n -> n.startsWith("to"))
.distinct().sorted()
.forEach(System.out::println);
The list includes toCharArray, toLowerCase, toString and toUpperCase.
Frequently Asked Questions
How do frameworks like JUnit use annotations?
JUnit uses reflection to find every method marked @Test and calls each one. Spring finds classes marked @Component and creates them for you. The annotations themselves do nothing; the framework code that reads them does the work.
Do annotations slow down my program?
No. An annotation is just data attached to the class. Only the code that reads it with reflection costs time, and frameworks usually do that once, at start-up.
Summary
- Annotations add information to code; some are checked by the compiler.
- Declare custom annotations with
@interface, plus@Retentionand@Target. - Reflection reads classes, fields, annotations and methods at run time.
- Use reflection for tools and frameworks, not for everyday logic.
Next: Immutable Objects in Java.
