3

例如,一个类Exam有一些带有注释的方法。

@Override
public void add() {
    int c=12;
}

如何获取具有@Override注释的方法名称(添加) org.eclipse.jdt.core.IAnnotation

4

3 回答 3

7

您可以在运行时使用反射来执行此操作。

public class FindOverrides {
   public static void main(String[] args) throws Exception {
      for (Method m : Exam.class.getMethods()) {
         if (m.isAnnotationPresent(Override.class)) {
            System.out.println(m.toString());
         }
      }
   }
}

编辑:要在开发时间/设计时间这样做,您可以使用此处描述的方法。

于 2012-06-11T12:46:50.843 回答
5

IAnnotation具有很强的误导性,请参阅文档。

从具有一些注释的类中检索方法。为此,您必须遍历所有方法并仅生成具有此类注释的方法。

public static Collection<Method> methodWithAnnotation(Class<?> classType, Class<?  extends Annotation> annotationClass) {

  if(classType == null) throw new NullPointerException("classType must not be null");

  if(annotationClass== null) throw new NullPointerException("annotationClass must not be null");  

  Collection<Method> result = new ArrayList<Method>();
  for(Method method : classType.getMethods()) {
    if(method.isAnnotationPresent(annotationClass)) {
       result.add(method);
    }
  }
  return result;
}
于 2012-06-11T12:53:15.490 回答
1

另一个使用 AST DOM 的简单 JDT 解决方案如下:

public boolean visit(SingleMemberAnnotation annotation) {

   if (annotation.getParent() instanceof MethodDeclaration) {
        // This is an annotation on a method
        // Add this method declaration to some list
   }
}

您还需要访问NormalAnnotationMarkerAnnotation节点。

于 2014-11-11T09:58:57.113 回答