deem deem - 10 months ago 62
Java Question

How to access annotation variables from interceptor

Lets say I have simple annotation

@Retention(RUNTIME) @Target({TYPE, METHOD})
public @interface CheckUserRole {
@Nonbinding String[] allowedRoles() default "";

Next, I have interceptor defined like this:

public class CheckUserRoleInterceptor

How can I access
from annotation? I'm doing it this way:

CheckUserRole checkUserRoleAnnotation = ctx.getMethod().getAnnotation(CheckUserRole.class);

if(checkUserRoleAnnotation != null){
String[] allowedRoles = checkUserRoleAnnotation.allowedRoles();

But this only works if I use annotation on method in my class. If I want to use my annotation on whole class,
, since my method ins't annotated in code with it.

How can I access those variables when whole class is annotated?

Answer Source

I've found good solution for this problem. To access annotation from method or class (if there is no annotation on method level) just use my function:

// Returns annotation from method or class (if does not exist, returns null)
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object getAnnotationClass(Class clazz, InvocationContext ctx){
    Object annotationClass = ctx.getMethod().getAnnotation(clazz);

    // Try to find annotation on class level
    if(annotationClass == null){
        annotationClass = ctx.getTarget().getClass().getSuperclass().getAnnotation(clazz);

    return annotationClass;

My function does:

  1. Check if there is annotation on method level
  2. If not, check if there is annotation on class level
  3. If still not, return null

Note using .getSuperclass() since .getClass() returns proxy.

Example of usage:

CheckUserRole annotationClass = (CheckUserRole) getAnnotationClass(CheckUserRole.class, ctx);   

if(annotationClass != null){
    String[] allowedRoles = annotationClass.allowedRoles();