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