例如,一个类Exam
有一些带有注释的方法。
@Override
public void add() {
int c=12;
}
如何获取具有@Override
注释的方法名称(添加) org.eclipse.jdt.core.IAnnotation
?
例如,一个类Exam
有一些带有注释的方法。
@Override
public void add() {
int c=12;
}
如何获取具有@Override
注释的方法名称(添加) org.eclipse.jdt.core.IAnnotation
?
您可以在运行时使用反射来执行此操作。
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());
}
}
}
}
编辑:要在开发时间/设计时间这样做,您可以使用此处描述的方法。
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;
}
另一个使用 AST DOM 的简单 JDT 解决方案如下:
public boolean visit(SingleMemberAnnotation annotation) {
if (annotation.getParent() instanceof MethodDeclaration) {
// This is an annotation on a method
// Add this method declaration to some list
}
}
您还需要访问NormalAnnotation
和MarkerAnnotation
节点。