问题
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