在做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;
}
}