java - 提交对 JDT CompilationUnit 的更改

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

大家好

我正在尝试为 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

Class after(根据上面代码运行后CompilationUnit的toString())

enter image description here

显然,方法声明已按照我的意愿创建,但我无法弄清楚如何将此类更改提交给底层资源。我找到的唯一方法是 ICompilationUnit 中的提交方法,但它已被弃用,你能建议任何其他方式?

最佳答案

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

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);
    }

关于java - 提交对 JDT CompilationUnit 的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34909384/

相关文章:

java - 比较运算符问题

java - Spring Security 两个网站共享相同的记住我登录

java - DOM4J xpath-选择带有命名空间的冒号节点

eclipse - 如何更改打开视角图标?

android - 命令 "Fix Project Properties"究竟做了什么?

c++ - clang 3.8 - 如何阻止 clang 创建系统 header 的 AST?

java - 如何访问 INRIA-SPOON 中的 "this"变量

java - NetBeans 7.0.1 : Access to Tomcat server has not been authorized

java - 尝试在 eclipse 中安装 mase 插件时出现错误消息

ocaml - 是否可以在 OCaml 中直接将 "type"作为字符串打印出来?