Getting Annotations from Class Objects
You'll learn how to retrieve annotations attached to classes at runtime using the Reflection API.
Understanding Annotation Retrieval
Once annotations have runtime retention (as you learned previously), you can query them from Class objects using reflection. Java provides three key methods for this:
getAnnotations()– Returns all inherited annotations (those present on the class and inherited from superclasses)getDeclaredAnnotations()– Returns only annotations directly declared on this class (no inheritance)getAnnotation(Class<T>)– Returns a specific annotation by type, ornullif absent
Think of these methods like searching a filing cabinet: getAnnotations() checks the current drawer and parent folders, getDeclaredAnnotations() checks only the current drawer, and getAnnotation(Class) searches for one specific document by name.
How It Works
Class<?> clazz = MyClass.class;
// Get all annotations (including inherited ones)
Annotation[] allAnnotations = clazz.getAnnotations();
// Get only annotations declared directly on this class
Annotation[] declaredOnly = clazz.getDeclaredAnnotations();
// Get a specific annotation by type
MyCustomAnnotation specific = clazz.getAnnotation(MyCustomAnnotation.class);
if (specific != null) {
// Access annotation properties
String value = specific.value();
}
The returned annotation objects act as proxies—you can call their methods to retrieve the values you defined when you applied the annotation.
When to Use Which Method
Use getAnnotations() when you care about inherited metadata (like @Inherited annotations from frameworks). Use getDeclaredAnnotations() when you only want class-specific metadata. Use getAnnotation(Class) when you know exactly which annotation you're looking for.
Key Takeaway: Use getAnnotations(), getDeclaredAnnotations(), and getAnnotation(Class) to reflectively retrieve annotations from class objects—choosing the method that matches whether you need inherited or declared-only metadata.