版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sr19930829/article/details/83029649
/*
* javaFilePath 文件的绝对路径,比如: D:\test\javatp\1B\14638316\14638316.java
* javaName 文件名,比如: 14638316.java
* fileDir 文件的所在文件夹路径,比如: D:\test\javatp\1B\14638316
*/
public static CompilationUnit getCompilationUnit(String javaFilePath, String javaName, String fileDir){
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();
}
Map<String, String> options = JavaCore.getOptions();
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
JavaCore.VERSION_1_8);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
ASTParser astParser = ASTParser.newParser(AST.JLS4);
astParser.setSource(new String(input).toCharArray());
astParser.setKind(ASTParser.K_COMPILATION_UNIT);
astParser.setEnvironment( // apply classpath
new String[] { "D:\\Program Files\\Java\\jdk1.8.0_181\\src.zip" }, //
new String[]{fileDir}, new String[] { "UTF-8" }, true);
astParser.setBindingsRecovery(true);
astParser.setResolveBindings(true);
astParser.setStatementsRecovery(true);
astParser.setBindingsRecovery(true);
astParser.setUnitName(javaName);
astParser.setCompilerOptions(options);
CompilationUnit compilationUnit = (CompilationUnit) (astParser.createAST(null));
List<?> types = compilationUnit.types();
TypeDeclaration typeDeclaration = (TypeDeclaration) types.get(0);
ITypeBinding binding = typeDeclaration.resolveBinding();
//System.out.println("Analysing type: " + binding.getName());
return compilationUnit;
}
这种方式可以获得Binding信息,但不可以获取IJavaElement。