Retrieving method annotations with Spring AnnotationUtils
Spring ·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.
1 getAnnotation method
Signature:
public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType)
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:
public class Foo<T> { public T aMethod(T param) { return param; } } public class Bar extends Foo<String> { @MyAnnotation public String aMethod(String param) { return param; } }
Now we try to retrieve @MyAnnotation with both utility methods:
Method barAMethod = Bar.class.getMethod("aMethod", Object.class); System.out.println("getAnnotation (JDK): " + barAMethod.getAnnotation(MyAnnotation.class)); System.out.println("getAnnotation (Spring): " + AnnotationUtils.getAnnotation(barAMethod, MyAnnotation.class));
The result is as follows:
2 findAnnotation method
Signature:
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType)
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:
public class Foo { @MyAnnotation public void anotherMethod() { //... } } public class Bar extends Foo { @Override public void anotherMethod() { //... } }
Trying to retrieve @MyAnnotation from anotherMethod in Bar class using the different utility methods
Method barAnotherMethod = Bar.class.getMethod("anotherMethod"); System.out.println("getAnnotation (JDK): " + barAnotherMethod.getAnnotation(MyAnnotation.class)); System.out.println("getAnnotation (Spring): " + AnnotationUtils.getAnnotation(barAnotherMethod, MyAnnotation.class)); System.out.println("findAnnotation (Spring): " + AnnotationUtils.findAnnotation(barAnotherMethod, MyAnnotation.class));
will get the following results: