maven依賴
<dependency>
<groupId>org.eclipse.jdt</groupId>
<artifactId>org.eclipse.jdt.core</artifactId>
<version>3.13.0</version>
</dependency>
代碼:
import org.apache.commons.io.FileUtils;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import java.io.File;
import java.util.Map;
import static org.eclipse.jdt.core.dom.AST.JLS8;
public class JdtTest {
public static void main(String[] args) {
ASTParser parser = ASTParser.newParser(AST.JLS8); //設置Java語言規范版本
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setCompilerOptions(null);
parser.setResolveBindings(true);
Map<String, String> compilerOptions = JavaCore.getOptions();
compilerOptions.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); //設置Java語言版本
compilerOptions.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
compilerOptions.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
parser.setCompilerOptions(compilerOptions); //設置編譯選項
String src = null;
try {
src = FileUtils.readFileToString(new File("LoginController.java"),"UTF-8"); //要解析的文件
} catch (Exception e) {
e.printStackTrace();
}
parser.setSource(src.toCharArray());
CompilationUnit cu = (CompilationUnit) parser.createAST(null); //下個斷點可以看看cu的types成員就是整個語法樹
System.out.println(cu);
}
}