Reading history

Java Annotations and Reflection With a Custom Validator

6 min read 0 views

Learn Java's built-in annotations, create custom annotations with @Retention and @Target, and read them with reflection to build a simple validator.

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, @Deprecated and @SuppressWarnings do
  • Declaring your own annotation with @interface
  • @Retention and @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]
  • @Override asks the compiler to check that the method really overrides one in a parent class. A typo such as sond() then becomes a compile error instead of a silent new method.
  • @FunctionalInterface makes 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.
  • @SuppressWarnings silences specific warnings, here about the raw List type 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 MaxLength declares an annotation with one setting, value, so it can be written as @MaxLength(10). @NotBlank has 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.
  • validate knows nothing about sign-up forms. It asks the object’s class for its fields (getDeclaredFields), reads each value with f.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 with toUpperCase.

Retention Policies

RetentionKept untilUsed by
SOURCECompilation onlyCompiler checks such as @Override
CLASS (default)The .class file, but not loaded at run timeBuild tools that read class files
RUNTIMEWhile the program runsReflection, frameworks, validators

Common Mistakes

  1. Forgetting @Retention(RUNTIME), so getAnnotation always returns null.
  2. 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.
  3. Reading private fields of other classes. This needs setAccessible(true), which can be blocked by the module system.
  4. 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 @Retention and @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.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *