How can I get the method name which has annotation?

邮差的信 提交于 2019-12-12 14:13:30

问题


A class for example Exam has some methods which has annotation.

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

How can I get the method name (add) which has @Override annotation using org.eclipse.jdt.core.IAnnotation?


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



回答2:


You can use reflection to do so at runtime.

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

Edit: To do so during development time/design time, you can use the method described here.




回答3:


Another simple JDT solution employing AST DOM can be as below:

public boolean visit(SingleMemberAnnotation annotation) {

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

You also need to visit the NormalAnnotation and MarkerAnnotation nodes.



来源:https://stackoverflow.com/questions/10980283/how-can-i-get-the-method-name-which-has-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!