Monday, May 13, 2013

Retrieving method annotations with Spring Annotation Utils

1   Introduction

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 framework included a general utility class for annotations, org.springframework.core.annotation.AnnotationUtils, 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

Signature:
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:



3   findAnnotation method

Signature:
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:



No comments:

Post a Comment