I have an inteface Foo with an implementation Bar. The interface Foo has a method “doMe()” with a method annotation @Secured. This is the only method that is secured.
Now I wrote the following code to go through classes and look for methods with @Secured on them. (This method is not finished yet, I’m trying to get the first unit tests passed.)
/**
* Determine if a method is secured
* @param method the method being checked
* @return true if the method is secured, false otherwise
*/
protected static boolean isSecured(Method method) {
boolean secured = false;
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation:annotations){
if(Secured.class.equals(annotation.getClass())){
secured = true;
break;
}
}
if(secured){
return true;
}
return secured;
}
Methods besides doMe() return 0 members on getAnnotations() for both Foo and Bar. The problem is that doMe() also returns 0 members for both Foo and Bar.
I’m looking for someone that knows more about reflection than me, since that shouldn’t be hard to find. 🙂
Thanks.
Have you ensured that the annotation is visible at runtime? You may need to annotate your annotation with
@Retention(RetentionPolicy.RUNTIME). The default,CLASS, won’t return the annotation in reflective methods.See also: RetentionPolicy docs