ASTParser中binding没有成功绑定,导致resolveTypeBinding()返回null

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)才跑的出结果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值