pro*_*eek 1 java eclipse eclipse-plugin abstract-syntax-tree eclipse-jdt
我有一个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
Run Code Online (Sandbox Code Playgroud)
如何将此修改后的单元保存到新文件中?
您可以使用a 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.
Run Code Online (Sandbox Code Playgroud)
检查以下链接.这样可以深入了解如何将AST更改写入文件.
http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html
更新: 这是我写入文件的方式:
File file = new File(destFile);
FileUtils.writeStringToFile(File file, String newSource)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1853 次 |
| 最近记录: |