使用JDT轉java代碼為AST


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);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM