使用 Eclipse 插件将修改后的 AST 保存在新文件中 [英] Saving modified AST in a new file with eclipse plugin

查看:54
本文介绍了使用 Eclipse 插件将修改后的 AST 保存在新文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Eclipse 插件代码来操作项目/工作区中的类 (smcho.Hello).我可以创建一个 CompilationUnit 并对其进行一些修改,但我需要将结果保存在不同的文件中以检查两个版本之间的差异.

I have a eclipse plugin code to manipulate a class (smcho.Hello) in a project/workspace. I could create a CompilationUnit and did some modifications on it, but I need to save the result in different file to check the differences between the two version.

这是我如何获得 CompilationUnit 的代码.

This is the code how I get the 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

如何将修改后的单元保存到新文件中?

How can I save this modified unit into a new file?

推荐答案

您可以使用 ASTRewriter 来做到这一点.

You can use an ASTRewriter to do so.

// 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 更改写入文件的见解.

Check the link below. This gives insight on how to write the AST changes to the file.

http://www.eclipse.org/article/article.php?file=Article-JavaCodeManipulation_AST/index.html

更新:这是我写入文件的方式:

Update: This is how i write to the file:

File file = new File(destFile);
FileUtils.writeStringToFile(File file, String newSource) 

这篇关于使用 Eclipse 插件将修改后的 AST 保存在新文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆