【代码重构 & 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。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值