请写一个java代码格式化工具
时间: 2023-12-13 16:02:41 浏览: 66
代码格式化工具
以下是一个简单的 Java 代码格式化工具,使用了 Java 编译器的 API:
```java
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class JavaCodeFormatter {
private static final String INDENTATION = " "; // 4 spaces
public static void main(String[] args) throws IOException {
Path filePath = Path.of("path/to/java/file.java");
String source = Files.readString(filePath, StandardCharsets.UTF_8);
Context context = new Context();
JavaFileObject sourceFile = JavacTool
.create().getTask(null, null, null, null, null,
List.of(new SourceFile(sourcePath.toString())), context)
.call()
.iterator()
.next()
.getSourceFile();
JavacTrees trees = JavacTrees.instance(context);
JCCompilationUnit compilationUnit = (JCCompilationUnit) trees
.parse(sourceFile);
TreePathScanner<Void, Void> scanner = new TreePathScanner<>() {
private int indentationLevel = 0;
@Override
public Void visitVariable(JCVariableDecl variableDecl, Void aVoid) {
variableDecl.mods.annotations = variableDecl.mods.annotations.stream()
.sorted((a, b) -> a.toString().compareToIgnoreCase(b.toString()))
.collect(Collectors.toList());
return super.visitVariable(variableDecl, aVoid);
}
@Override
public Void visitClassDef(JCTree.JCClassDecl classDecl, Void aVoid) {
printIndented("class " + classDecl.getSimpleName());
if (classDecl.getExtendsClause() != null) {
printIndented("extends " + classDecl.getExtendsClause());
}
if (!classDecl.getInterfaces().isEmpty()) {
printIndented("implements " + classDecl.getInterfaces());
}
printIndented("{");
indentationLevel++;
List<JCTree> members = classDecl.getMembers();
for (int i = 0; i < members.size(); i++) {
JCTree member = members.get(i);
if (member instanceof JCVariableDecl) {
printIndented(((JCVariableDecl) member).toString() + ";");
} else {
printIndented(member.toString());
}
}
indentationLevel--;
printIndented("}");
return super.visitClassDef(classDecl, aVoid);
}
private void printIndented(String string) {
System.out.println(INDENTATION.repeat(indentationLevel) + string);
}
};
TreePath path = trees.getPath(compilationUnit);
scanner.scan(path, null);
}
}
```
这个代码格式化工具会读取指定的 Java 源码文件,使用 Java 编译器的 API 解析和遍历语法树,然后格式化输出。这个示例代码会把变量的注解按字母顺序排序,并且使用 4 个空格缩进。
阅读全文