本文介绍了从Eclipse插件向方法添加注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从Eclipse插件向方法添加注释。我可以访问表示特定方法的 IJavaElement
。
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.
使用Eclipse JDT的最佳方法是什么?
What would be the best approach using Eclipse JDT for this?
推荐答案
是的,JDT可能是解决此问题的好方法。
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.
}
这篇关于从Eclipse插件向方法添加注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!