本文主要是介绍【代码重构 JDT】获取指定目录下Java文件对应的ICompilationUnit (可获取Binding),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/** 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 classpathnew 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。
这篇关于【代码重构 JDT】获取指定目录下Java文件对应的ICompilationUnit (可获取Binding)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!