Course contentsShow
← Java
Lesson 2383 of 2,87045. Reflection APIFree lesson

Reading Annotations from Constructors and Parameters

Extracting annotations from Constructor objects and parameter annotations using getParameterAnnotations().

Reading Annotations from Constructors and Parameters

What you'll learn: How to extract annotation metadata from Constructor objects and their individual parameters using reflection.

The Core Idea

Just as you've been reading annotations from classes, methods, and fields, you can also inspect annotations attached to constructors and their parameters. This is crucial when frameworks need to understand how to instantiate objects based on metadata — for example, dependency injection frameworks that need to know which constructor to use and what to inject into each parameter.

Extracting Constructor Annotations

Once you have a Constructor object (via getConstructor() or getDeclaredConstructors()), you can call annotation retrieval methods directly on it:

Constructor<?> constructor = MyClass.class.getDeclaredConstructor(String.class, int.class);

// Get a specific annotation
Deprecated dep = constructor.getAnnotation(Deprecated.class);

// Get all annotations
Annotation[] annotations = constructor.getAnnotations();

Reading Parameter Annotations

Constructors often have parameters, and those parameters can be annotated too. Use getParameterAnnotations() to retrieve a two-dimensional array of annotations — one array per parameter:

Annotation[][] paramAnnotations = constructor.getParameterAnnotations();

// paramAnnotations[0] = annotations on first parameter
// paramAnnotations[1] = annotations on second parameter

for (int i = 0; i < paramAnnotations.length; i++) {
    System.out.println("Parameter " + i + ":");
    for (Annotation ann : paramAnnotations[i]) {
        System.out.println("  " + ann);
    }
}

Think of it like this: The outer array represents each parameter slot, and the inner arrays contain all annotations decorating that specific parameter.

Key Takeaway: Use Constructor.getAnnotation() for constructor-level annotations and Constructor.getParameterAnnotations() to retrieve a 2D array of annotations on constructor parameters — essential for frameworks that need fine-grained instantiation control.