Javaparser是一個(gè)用Java編寫(xiě)的解析器庫(kù),它可以用來(lái)解析、檢查、修改和生成Java源代碼。下面是使用Javaparser的簡(jiǎn)單示例:
<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來(lái)解析Java源代碼文件的簡(jiǎn)單示例。您可以進(jìn)一步探索Javaparser的功能,以進(jìn)行更復(fù)雜的源代碼分析和修改。