在JDT CompilationUnit上提交更改

时间:2016-01-20 20:00:11

标签: java eclipse-plugin abstract-syntax-tree eclipse-jdt

Hellou家伙

我试图为eclipse创建插件以生成一些代码,并且我一直试图用JDT来操作源代码

这是一个例子

        final ASTParser parser = ASTParser.newParser(AST.JLS8); 
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource(copy);
        parser.setResolveBindings(true);

        ASTNode node = parser.createAST(null);

        CompilationUnit unit = (CompilationUnit) parser.createAST(null);

        AST ast = unit.getAST();

        MethodDeclaration declaration = ast.newMethodDeclaration();
        declaration.setName(ast.newSimpleName("test"));

        TypeDeclaration typeDeclaration = ( TypeDeclaration )unit.types().get( 0 );
        typeDeclaration.bodyDeclarations().add(declaration);

之前的课程

enter image description here

之后的类(在运行上面的代码之后根据CompilationUnit的toString())

enter image description here

显然,我已经按照自己的意愿创建了方法声明,但我无法弄清楚如何将这些更改提交给底层资源。我发现的唯一方法是在ICompilationUnit中提交方法,但是不推荐,你能建议其他方式吗?

1 个答案:

答案 0 :(得分:1)

好的,感谢bodo的评论,我已经弄明白了

private void saveChanges(ICompilationUnit copy, CompilationUnit unit)
            throws JavaModelException, MalformedTreeException, BadLocationException {

        Document document= new Document(copy.getBuffer().getContents());
        TextEdit edits = unit.rewrite(document, copy.getJavaProject().getOptions(true));
        edits.apply(document);
        copy.getBuffer().setContents(document.get());
        copy.save(null, false);
    }