-->

保存修改AST在Eclipse插件的新文件(Saving modified AST in a new

2019-10-17 07:17发布

我有一个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

我怎么能这样修改单元保存到一个新文件?

Answer 1:

您可以使用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

更新:这是我写的文件:

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


Answer 2:

这是我可以用节省重写AST到另一个文件中的代码。 我不知道是否有可能是更简单的方法。

Document document = new Document(lwCompilationUnit.getSource());
rewrite.rewriteAST().apply(document);
String source = document.get();
String destFile = "...";
Helper.toFile(source, destFile);

public static void toFile(String source, String outputPath)
{
   try{
          // Create file 
          FileWriter fstream = new FileWriter(outputPath);
          BufferedWriter out = new BufferedWriter(fstream);
          out.write(source);
          //Close the output stream
          out.close();
    }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
    }
}


文章来源: Saving modified AST in a new file with eclipse plugin