利用Eclipse JDT ASTRewrite添加注释

1、修改前

public class Main {
    public static void main(String[] args) {
        int i = 1;
        System.out.println(i);
    }
    public static void add() {
        int i = 1;
        System.out.println(i);
    }
}

2、修改后

public class Main {
    public static void main(String[] args) {
        //mycomment
        int i = 1;
        System.out.println(i);
    }
    public static void add() {
        int i = 1;
        System.out.println(i);
    }
}

3、源码

private void AddComments() throws MalformedTreeException, BadLocationException, CoreException {

    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("testAddComments");
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragment package1 = javaProject.getPackageFragments()[0];

    //get first compilation unit
    ICompilationUnit unit = package1.getCompilationUnits()[0];

    // parse compilation unit
    CompilationUnit astRoot = parse(unit);

    //create a ASTRewrite
    AST ast = astRoot.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);

    //for getting insertion position
    TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0);
    MethodDeclaration methodDecl = typeDecl.getMethods()[0];
    Block block = methodDecl.getBody();

    ListRewrite listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
    Statement placeHolder = (Statement) rewriter.createStringPlaceholder("//mycomment", ASTNode.EMPTY_STATEMENT);
    listRewrite.insertFirst(placeHolder, null);

    TextEdit edits = rewriter.rewriteAST();

    // apply the text edits to the compilation unit
    Document document = new Document(unit.getSource());

    edits.apply(document);

    // this is the code for adding statements
    unit.getBuffer().setContents(document.get());

    System.out.println("done");
}

你可能感兴趣的:(eclipse,jdt,ast,java)