如何获取具有注释的方法名称?

Anu*_*Anu 3 java eclipse-plugin eclipse-jdt

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

@Override
public void add() {
    int c=12;
}
Run Code Online (Sandbox Code Playgroud)

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

Apo*_*sia 5

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

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

编辑:要在开发时间/设计时间内执行此操作,您可以使用此处描述的方法.


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