Javaparser是一個用Java編寫的解析器庫,它可以用來解析、檢查、修改和生成Java源代碼。下面是使用Javaparser的簡單示例:
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.28.0</version>
</dependency>
HelloWorld.java
:public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("HelloWorld.java");
CompilationUnit cu = JavaParser.parse(in);
cu.findAll(ClassOrInterfaceDeclaration.class).forEach(clazz -> {
System.out.println("Class name: " + clazz.getName());
clazz.findAll(MethodDeclaration.class).forEach(method -> {
System.out.println("Method name: " + method.getName());
});
});
}
}
Class name: HelloWorld
Method name: main
這就是使用Javaparser來解析Java源代碼文件的簡單示例。您可以進一步探索Javaparser的功能,以進行更復雜的源代碼分析和修改。