package Ast;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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;
public class JdtAstUtil {
/**
* get compilation unit of source code
* @param javaFilePath
* @return CompilationUnit
*/
public static CompilationUnit getCompilationUnit(String javaFilePath){
byte[] input = null;
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(javaFilePath));
input = new byte[bufferedInputStream.available()];
bufferedInputStream.read(input);
bufferedInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ASTParser astParser = ASTParser.newParser(AST.JLS8);
astParser.setResolveBindings(true); //打开绑定
astParser.setSource(new String(input).toCharArray());
astParser.setKind(ASTParser.K_COMPILATION_UNIT); //K_COMPILATION_UNIT:编译单元,即一个Java文件,是所需解析的代码的类型
//最重要的两步
astParser.setEnvironment(null, null, null, true); //setEnvironment(classpath,sourcepath,encoding,true)
astParser.setUnitName("example.java"); //参数随意
CompilationUnit result = (CompilationUnit) (astParser.createAST(null));
return result;
}
}
在使用setSource(char [])方法的时候,后面要加上setEnvironment和setUnitName方法。setEnvironment方法单独使用是可以加入具体参数,但是setUnitName方法也使用的时候,参数只能用(null, null, null, true)才跑的出结果。