-->

我怎样才能得到它有注释的方法叫什么名字?(How can I get the method name

2019-09-18 00:52发布

A为例类Exam有一些方法,其中有注释。

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

我怎样才能获得方法名称(添加),其中有@Override使用注释org.eclipse.jdt.core.IAnnotation

Answer 1:

The IAnnotation is strongly misleading, please see the documentation.

To retrieve the Methods from Class that have some annotation. To do that you have to iterate through all methods and yield only those that have such annotation.

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


Answer 2:

您可以使用反射在运行时这样做。

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

编辑:为了在开发时间/设计时间这样做,你可以使用所描述的方法在这里 。



Answer 3:

另一种简单的JDT溶液采用AST DOM可以是如下:

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节点。



文章来源: How can I get the method name which has annotation?