Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding annotations on an interface

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.

like image 764
Thom Avatar asked Nov 27 '25 14:11

Thom


2 Answers

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

like image 99
Jeff Bowman Avatar answered Nov 29 '25 05:11

Jeff Bowman


Try using getAnnotation instead of getAnnotations, because getAnotations internally uses getDeclaredAnnotations.

More details at Method (Java Platform SE 6)

protected static boolean isSecured(Method method) {

        Secured secured = method.getAnnotation(Secured.class);

        return secured == null ? false : true;
    }
like image 24
Daya Avatar answered Nov 29 '25 03:11

Daya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!