简体   繁体   中英

How can I get the method name which has annotation?

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 ?

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM