我使用带有以下依赖项的JavaParser:
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.24.0</version>
</dependency>当我尝试将它与下面的类(解析本身)一起使用时.
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Some comment.
*/
public class JavaParserPlayground {
public static void main(String[] args) throws IOException {
// Some comment.
String source = Files.readString(Paths.get("path\\JavaParserPlayground.java"),
StandardCharsets.UTF_8);
// Some comment.
JavaParser parser = new JavaParser();
ParseResult<CompilationUnit> parseResult = parser.parse(source);
// Some comment.
CompilationUnit unit = parseResult.getResult().orElseThrow();
System.out.println(unit.toString());
}
}...then我得到以下结果:
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Some comment.
*/
public class JavaParserPlayground {
public static void main(String[] args) throws IOException {
// Some comment.
String source = Files.readString(Paths.get("path\\JavaParserPlayground.java"), StandardCharsets.UTF_8);
// Some comment.
JavaParser parser = new JavaParser();
ParseResult<CompilationUnit> parseResult = parser.parse(source);
// Some comment.
CompilationUnit unit = parseResult.getResult().orElseThrow();
System.out.println(unit.toString());
}
}我的问题是,我需要原始输出与所有原始行中断。但是它删除了一些空行(导入语句之间的空行,在方法中),删除了换行(在源赋值中)和adss空行(在main方法之前)。
更多:原始源有2个空格缩进,打印源4个空格。
是否有可能强制原始代码结构?
发布于 2022-01-28 07:06:53
您想要使用LexicalPreservingPrinter。这是设置文档。基本上,您可以像这样将它添加到链的末尾(当一切都按预期工作时):
CompilationUnit lpp = LexicalPreservingPrinter.setup(unit);
System.out.println(LexicalPreservingPrinter.print(lpp));https://stackoverflow.com/questions/70889680
复制相似问题