deem deem - 1 month ago 16
Java Question

How to access annotation variables from interceptor

Lets say I have simple annotation

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


Next, I have interceptor defined like this:

@Interceptor
@CheckUserRole
public class CheckUserRoleInterceptor


How can I access
allowedRoles
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,
checkUserRoleAnnotation
is
null
, since my method ins't annotated in code with it.

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

Answer

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();
}