`
sxw7362693
  • 浏览: 59618 次
  • 性别: Icon_minigender_1
  • 来自: 南京
文章分类
社区版块
存档分类
最新评论

JDT-AST Java文件源码分析示例--标记一下

阅读更多
AST对Java文件的结构解析--标记一下


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;

public class TestAST
{
	public static void main(String[] args)
	{
		String content = "";
		try
		{
			File file = new File("G:\\workspaces_base\\plugins_workspaces\\ToolbarDemo\\src\\com\\sxw\\toolbar\\TableViewer5.java");
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String record = null;
			int recCount = 0;
			while ((record = br.readLine()) != null)
			{
				recCount++;
				// System.out.println("Line " + recCount + ": " + record);
				content = content + record;
			}
			br.close();
			fr.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		ASTParser parsert = ASTParser.newParser(AST.JLS3);

		parsert.setSource(content.toCharArray());

		CompilationUnit result = (CompilationUnit) parsert.createAST(null);
		AST ast = result.getAST();

		List types = result.types();
		TypeDeclaration typeDec = (TypeDeclaration) types.get(0);

		List importList = result.imports();
		PackageDeclaration packetDec = result.getPackage();
		String className = typeDec.getName().toString();
		MethodDeclaration methodDec[] = typeDec.getMethods();
		FieldDeclaration fieldDec[] = typeDec.getFields();

		System.out.println("Field:");
		for(FieldDeclaration fieldDesc : fieldDec)
		{
			System.out.println(((VariableDeclarationFragment)fieldDesc.fragments().get(0)).getName().getFullyQualifiedName());
		}
		System.out.println("Method:");
		for (MethodDeclaration method : methodDec)
		{
			System.out.println(method.getName());
			// System.out.println(method.getBody());
			Block block = method.getBody();
			// 怎样继续下去得到上面代码1的第7行使用了ClassA 类和它的getClassbMethod 方法
		}

	}
}
 
分享到:
评论
1 楼 lywybo 2010-11-05  
hi,能共享下这个工程么,我需要依赖那些jar包呢?

相关推荐

Global site tag (gtag.js) - Google Analytics