当输入项目文件位于内存中而未保存为磁盘中的文件时,使用Spoon构建AST模型



我正在使用Spoon Inria来解析和分析Java应用程序。目前,我正在使用以下代码创建输入项目模型。当项目文件保存在磁盘中时,此代码有效。

Launcher spoonAPI = new Launcher();
spoonAPI.addInputResource(projectDirectory);  //The path to the project root directory
spoonAPI.buildModel();
CtModel ctModel = spoonAPI.getModel();

然而,目前我在内存中有Java文件(类(的内容,我不想把它们写在磁盘中,因为这需要很长时间。我想知道是否有一种使用Spoon的方法可以将文件内容传递给解析器。例如,下面的代码。

//Key is name of class and value is its content
Map<String, String> JavafileContents= new HashMap<String, String>();
for (String filePath : JavafileContents.keySet()) {
spoonAPI.parse(JavafileContents.get(filePath ));
}
CtModel ctModel = spoonAPI.getModel(); //The extracted model should contains all parsed files.

类似于JDT中提供的类似解决方案。

ASTParser parser = ASTParser.newParser(AST.JLS14);
parser.setSource(javaFileContents.get(filePath).toCharArray());
CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);

我也在寻找功能,我发现以下代码可能满足您的要求。

import spoon.support.compiler.VirtualFile;
...
public static CtClass<?> parseClass(String code) {
Launcher launcher = new Launcher();
launcher.addInputResource(new VirtualFile(code));
launcher.getEnvironment().setNoClasspath(true);
launcher.getEnvironment().setAutoImports(true);
...

来源是https://github.com/INRIA/spoon/blob/spoon-core-8.2.0/src/main/java/spoon/Launcher.java#L856.

或者,可以使用类似createCodeSnippetStatement的API

Factory factory = new Launcher().createFactory();
CtStatement tmpStmt = factory.Code().createCodeSnippetStatement(code);

选择API的方式取决于代码片段的类型(例如,表达式或语句(。

最新更新