I am trying to add an annotation to a method from an Eclipse plugin. I have access to the IJavaElement
that represents the particular method.
What would be the best approach using Eclipse JDT for this?
Yes JDT can be a good approach for this problem.
The following code will give you an idea of how to accomplish the same.
(note: code not tested nor compiled)
if (javaElement instanceof IMethod) {
// Get the compilation unit for traversing AST
final ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(javaElement.getCompilationUnit());
parser.setResolveBindings(true);
final CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
// Record modification - to be later written with ASTRewrite
compilationUnit.recordModifications();
// Get AST node for IMethod
int methodIndex = javaElement.getCompilationUnit().getSource().indexOf(javaElement.getSource());
ASTNode methodASTNode = NodeFinder.perform(compilationUnit.getRoot(), methodIndex, javaElement.getSource().length());
// Create the annotation
final NormalAnnotation newNormalAnnotation = methodASTNode.getAST().newNormalAnnotation();
newNormalAnnotation.setTypeName(methodASTNode.getAST().newName("AnnotationTest"));
// Add logic for writing the AST here.
}