大家好
我正在尝试为 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);
课前
Class after(根据上面代码运行后CompilationUnit的toString())
显然,方法声明已按照我的意愿创建,但我无法弄清楚如何将此类更改提交给底层资源。我找到的唯一方法是 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/