Pages

Wednesday, October 31, 2012

How you can get CompilationUnit (AST) from Workspace in eclipse?

The starting point is to get WorkSpace, and you can do that with ResourcePlugin#getWorkSpace() method. Eclipse workspaceClick to enlarge
You'll get a New Project with the right click in eclipse.
Screen Shot 2012 10 31 at 9 54 36 AM
You can get the project information using this code.
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
// Get all projects in the workspace
IProject[] projects = root.getProjects();
When you know the name of the project, you can find it.
IProject project = root.getProject("Hello");
Out of many project, you need only Java project.
IJavaProject javaProject = JavaCore.create(project);
Screen Shot 2012 10 31 at 9 54 59 AM

package fragments, compilation unit

Remember the package explorer in eclipse, you also have the project explorer. Inside a Java project, you'll find a lot of elements, which are called package fragments. From the package fragments, you normally want to use source code. getKind() method returns the property of the package fragment.
IPackageFragment[] packages = javaProject.getPackageFragments();
for (IPackageFragment mypackage : packages) {
    if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
Screen Shot 2012 10 31 at 10 56 30 AM Screen Shot 2012 10 31 at 10 54 30 AM
You can get the ICompilationUnit from package element.
IPackageFragment[] packages = JavaCore.create(project).getPackageFragments();
for (IPackageFragment mypackage : packages) {
	if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
		for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
			...
		}
	}
}
When you know the name of the type, you can get ICompilationUnit from it.
IType iType = javaProject.findType("PACKAGE_NAME.CLASS_NAME");
org.eclipse.jdt.core.ICompilationUnit iCompilationUnit = iType.getCompilationUnit();

parser and CompilationUnit

CompilationUnit is ASTNode that has the tree inside.
final ASTParser parser = ASTParser.newParser(AST.JLS3); 
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(iCompilationUnit);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit) parser.createAST(null);

Think

  • As you instantiate a specific object (JavaProject for example) from other object(Project for example), you can access the elements in the specific object.

References

1 comment:

  1. @prosseek,my project is a java explain project, not running in eclipse, how do I get all callers of a method?

    ReplyDelete