在界面上查找注释

Tho*_*hom 3 java reflection annotations

我有一个带有实现栏的接口Foo.接口Foo有一个带有方法注释@Secured的方法"doMe()".这是唯一受到保护的方法.

现在我编写了以下代码来浏览类并查找带有@Secured的方法.(此方法尚未完成,我正在尝试通过第一次单元测试.)

  /**
   * 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;
}
Run Code Online (Sandbox Code Playgroud)

除了doMe()之外的方法在foo和Bar的getAnnotations()上返回0个成员.问题是doMe()还为Foo和Bar返回0个成员.

我正在寻找一个比我更了解反思的人,因为这不应该很难找到.:)

谢谢.

Jef*_*ica 6

您是否确保注释在运行时可见?您可能需要使用注释注释@Retention(RetentionPolicy.RUNTIME).默认情况下,CLASS不会在反射方法中返回注释.

另请参阅:RetentionPolicy文档