我正在使用具有以下依賴項的 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());
}
}
...然后我得到以下結果:
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());
}
}
我的問題是我需要帶有所有原始換行符的原始輸出。但它會洗掉一些空行(在 import 陳述句之間,方法內),洗掉換行符(在源分配內)和廣告空行(在 main 方法之前)。
更多:原始來源有 2 個空格縮進,印刷來源有 4 個空格。
是否可以強制使用原始代碼結構?
uj5u.com熱心網友回復:
您想使用 LexicalPreservingPrinter。這是設定檔案。基本上,您可以像這樣將它添加到鏈的末尾(當一切按預期作業時):
CompilationUnit lpp = LexicalPreservingPrinter.setup(unit);
System.out.println(LexicalPreservingPrinter.print(lpp));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/422238.html
標籤:
