zoukankan      html  css  js  c++  java
  • 使用JDT.AST解析java源码

    在做java源码的静态代码审计时,最基础的就是对java文件进行解析,从而获取到此java文件的相关信息;

    在java文件中所存在的东西很多,很复杂,难以用相关的正则表达式去一一匹配。但是,eclipse 的一个插件

    jdt是一个已经封装好了的,对java文件进行解析的jar包。

    所需要的包:

    org.eclipse.core.contenttype_3.4.100.v20100505-1235.jar
    org.eclipse.core.jobs_3.5.0.v20100515.jar
    org.eclipse.core.resources_3.6.0.v20100526-0737.jar
    org.eclipse.core.runtime_3.6.0.v20100505.jar
    org.eclipse.equinox.common_3.6.0.v20100503.jar
    org.eclipse.equinox.preferences_3.3.0.v20100503.jar
    org.eclipse.jdt.core_3.6.0.v_A58.jar
    org.eclipse.osgi_3.6.0.v20100517.jar

    maven中:

    <dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>jdt</artifactId>
    <version>3.3.0-v20070607-1300</version>
    </dependency>
    <dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>org.eclipse.osgi</artifactId>
    <version>3.8.0.v20120529-1548</version>
    </dependency>
    <dependency>
    <groupId>org.eclipse.jdt</groupId>
    <artifactId>core</artifactId>
    <version>3.1.1</version>
    </dependency>

    调用方法:

     public class JdtAst {

    private ASTParser astParser = ASTParser.newParser(AST.JLS3); // 非常慢

    /**
    * 获得java源文件的结构CompilationUnit
    */
    public CompilationUnit getCompilationUnit(String filePath)
    throws Exception {

    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));//读取java文件
    byte[] input = new byte[bufferedInputStream.available()];
    bufferedInputStream.read(input);
    bufferedInputStream.close();
    this.astParser.setSource(new String(input).toCharArray());
    /**/
    CompilationUnit result = (CompilationUnit) (this.astParser
    .createAST(null)); // 很慢
    result.getImports();//通过result去获取java文件的属性,如getImports是获取java文件中import的文件的。
    return result;

    }
    }
     
  • 相关阅读:
    中文分词算法工具hanlp源码解析
    Hanlp分词1.7版本在Spark中分布式使用记录
    Window离线环境下如何安装pyhanlp
    如何编译运行HanLP自然语言处理包
    函数调用面试题
    构造函数复习
    面向对象的好处
    递归实现查找页面所有节点
    面向对象和原型
    chrome浏览器调试工具的使用
  • 原文地址:https://www.cnblogs.com/ermei/p/5833520.html
Copyright © 2011-2022 走看看