CodeBlanks Logo Icon CodeBlanks

Annotations via reflection

Learn to read annotations with reflection.

Reading annotations with getAnnotation

To read an annotation at runtime you use the getAnnotation method of the Class object. This works only for annotations with RUNTIME retention.

Example: Note n = Sample.class.getAnnotation(Note.class). Then n.value() accesses its element. If the annotation is absent the result is null; so it is safe to first check with isAnnotationPresent(Note.class). This mechanism lets frameworks discover classes automatically.

Safe checks with isAnnotationPresent

isAnnotationPresent returns a boolean for whether an annotation is present. Using it before getAnnotation gives safe access without a null check.

Example: if (c.isAnnotationPresent(Note.class)) { ... }. This pattern is common in frameworks: behavior changes based on whether a class carries a certain annotation. Checking several annotation types needs a separate call for each.

Practice Read the Note annotation with reflection

Define an @interface Note with String value(). Add @Retention(RetentionPolicy.RUNTIME) and @Target(ElementType.TYPE) above it. Apply @Note("hello") to the Sample class. In main, read the value with getAnnotation and print it with System.out.println.

Starter code

Main.java
// Define the Note annotation (RUNTIME, TYPE)
// Apply Note to the Sample class
// Read the value in main and print it

Sample solution

Main.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Note { String value(); }

@Note("hello")
class Sample { }

public class NoteReader {
    public static void main(String[] args) {
        Note n = Sample.class.getAnnotation(Note.class);
        System.out.println(n.value());
    }
}

Expected output

hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the reflection methods

Term Meaning
getAnnotation Returns a single annotation
isAnnotationPresent Presence check
getAnnotations Array of all annotations
value() Element access

2 Complete the getAnnotation call

Question
Note n = Sample.class.getAnnotation(____.class);
Answer
Note n = Sample.class.getAnnotation(Note.class);

Explanation: The annotation class object is passed as the parameter.

3 What does getAnnotation return when the annotation is absent?

  • An empty array
  • false
  • null Correct answer
  • Throws IllegalAccessException

Explanation: It returns null; that is why checking is safe.

All lessons in Advanced