AST解析java源文件相关jar包

阅读更多
今天有个处理需要涉及到java源文件的解析,baidu、google搜索了下,知道 eclipse 的 AST 可以解析java源文件,做了测试,老是报出异常来,后来发现是相关jar包少了,以免各位朋友犯同样的错误,把用到的相关jar文件贴出来,附件就是这些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


贴段相关代码:
import java.io.BufferedInputStream;
import java.io.FileInputStream;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;

/**
 * java源文件解析操作
 * @author linym
 * @version 2010-08
 */
public class JdtAst {

	private ASTParser astParser = ASTParser.newParser(AST.JLS3);//非常慢
	
	/**
	 * 获得java源文件的结构CompilationUnit
	 * @param javaFilePath java文件的绝对路径
	 * @return CompilationUnit
	 * @throws Exception
	 */
    public CompilationUnit getCompilationUnit(String javaFilePath) throws Exception {
    	
        BufferedInputStream bufferedInputStream = new BufferedInputStream(
                new FileInputStream(javaFilePath));
        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));//很慢
        
        return result;
//        List commentList = result.getCommentList();
//        PackageDeclaration package1 = result.getPackage();
//        List importList = result.imports();
//        TypeDeclaration type = (TypeDeclaration) result.types().get(0);
//        FieldDeclaration[] fieldList = type.getFields();
//        MethodDeclaration[] methodList = type.getMethods();
//        Block method_block=methodList[1].getBody();
//        TryStatement try_stmt=(TryStatement)method_block.statements().get(0);
//        ForStatement for_stmt=(ForStatement)try_stmt.getBody().statements().get(0);
//        ExpressionStatement express_stmt=(ExpressionStatement) ((Block)for_stmt.getBody()).statements().get(0);
       
    }
}
  • AST解析java源文件jar.rar (6.1 MB)
  • 下载次数: 941

你可能感兴趣的:(Java,Eclipse,OSGI,Google)