Retrieving method annotations with Spring AnnotationUtils

1 Introduction to Spring AnnotationUtils

The JDK provides us with several lookup methods that allow us to retrieve annotations from a class, method, field or added to method parameters. The Spring AnnotationUtils is a general utility class for annotations which extends the basic functionalities. In this post I will explain the main features of this class, focusing on retrieving annotations from a method.

2 getAnnotation method


This method looks up if method contains the specified annotation type and returns it if found. So, what’s the difference between the JDK getAnnotation method? The Spring version handles bridge methods. You can check effects of Type Erasure and Bridge Methods tutorial to get a good explanation.

Let’s see it with an example. Imagine we got a generic class Foo, and a Bar class that extends it:


Now we try to retrieve @MyAnnotation with both utility methods:

The result is as follows:

getAnnotation result

3 findAnnotation method


This method also retrieves the specified annotation type from method. The difference between getAnnotation is that in this case, it will look up the entire inheritance hierarchy of the specified method.

Let’s see another example. We got the classes below:

Trying to retrieve @MyAnnotation from anotherMethod in Bar class using the different utility methods

will get the following results:

findAnnotation result


Share it:

Leave a Reply

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