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 方法
		}

	}
}
 

你可能感兴趣的:(java,eclipse)