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

Extracting Annotation Element Values

Invoking annotation methods to retrieve element values like strings, enums, classes, and arrays from annotation instances.

Extracting Annotation Element Values

What you'll learn: How to invoke methods on annotation instances to retrieve element values like strings, enums, classes, and arrays.

When you obtain an annotation instance through reflection (from a class, method, field, etc.), you don't just get a label—you get access to all the data stored in that annotation's elements. Think of an annotation like a form filled with information; extracting element values means reading what was written in each field.

How Annotation Elements Work

Annotation elements are declared as methods in the annotation definition, but they're accessed like properties. When you call these methods on an annotation instance, you're retrieving the values that were specified when the annotation was applied.

For example, if you have @MyAnnotation(name="Test", priority=5), you extract those values by calling name() and priority() on the annotation object.

Accessing Element Values

Once you've retrieved an annotation (using getAnnotation(), getDeclaredAnnotation(), etc.), simply invoke its element methods:

MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String name = annotation.name();
int priority = annotation.priority();

Different Element Types

  • Strings and primitives: Call the method directly, get the value
  • Enums: Return the specific enum constant
  • Classes: Return Class<?> objects via methods like value()
  • Arrays: Return arrays of the element type (strings, classes, etc.)

Array elements are particularly useful: String[] tags = annotation.tags(); gives you all values in one call.

Key Takeaway: Annotation element values are extracted by calling methods on the annotation instance—each element method returns its configured value, whether primitive, String, enum, Class, or array type.