从Eclipse插件向方法添加注释

时间:2014-10-16 05:14:22

标签: eclipse-plugin refactoring eclipse-jdt

我正在尝试从Eclipse插件向方法添加注释。我可以访问代表特定方法的IJavaElement

使用Eclipse JDT的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

是的JDT可以解决这个问题。

以下代码将让您了解如何完成相同的操作 (注意:代码未经测试也未编译)

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.

}