1. 程式人生 > >【程式碼重構 & JDT】獲取指定目錄下Java檔案對應的ICompilationUnit (可獲取Binding)

【程式碼重構 & 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 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。