我有一个 Eclipse 插件代码来操作项目/工作空间中的类 (smcho.Hello)。
我可以创建一个 CompilationUnit 并对其进行一些修改,但我需要将结果保存在不同的文件中以检查两个版本之间的差异。
这是我获取 CompilationUnit 的代码。
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("Hello");
project.open(null);
IJavaProject javaProject = JavaCore.create(project);
IType lwType = javaProject.findType("smcho.Hello");
org.eclipse.jdt.core.ICompilationUnit lwCompilationUnit = lwType.getCompilationUnit();
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(lwCompilationUnit);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit) parser.createAST(null /* IProgressMonitor */);
// modify the unit AST node
如何将修改后的单元保存到新文件中?
您可以使用ASTRewriter
这样做。
// get the ast rewriter
final ASTRewrite rewriter = ASTRewrite.create(ast);
// get the current document source
final Document document = new Document(unit.getSource());
// compute the edits you have made to the compilation unit
final TextEdit edits = rewriter.rewriteAST();
// apply the edits to the document
edits.apply(document);
// get the new source
String newSource = document.get();
// now write this source to some other file.
检查下面的链接。这让我们深入了解如何将 AST 更改写入文件。
http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html
Update:这就是我写入文件的方式:
File file = new File(destFile);
FileUtils.writeStringToFile(File file, String newSource)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)