javaeclipse-pluginswtjfaceeclipse-api

Eclispe API - How to get parent project location


How to get the parent module of project. Here is my code works fine in Eclipse PDE. But when I test the plugin(installing in eclipse) using test application by selecting the child module this condition (if (projectRoot == selectedResource)) is coming true and it return src and target as child modules which is incorrect. Any suggestion on how to get the parent module of project.

IResource selectedResource = Resource.getSelectedProject(); // this return selected module (F/parent/child1)
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();  // \R
// this is not returning parent module??
IProject projectRoot = root.getProject(selectedResource.getProject().getName()); 
List<IResource> childModules = new ArrayList<>();

if (projectRoot == selectedResource) { // this is coming true (parent != child)
    IProject project = FileResource.getProject(selectedResource);
    childModules = Resource.getChildModules(project);
} else {
    childModules.add(selectedResource);
}

Resource.Class

private static IResource selectedResource;

public static void setSelectedResource(IResource resource) {
    selectedResource = resource;
 }

public static IResource getSelectedProject() {
    return selectedResource;
 }

Solution

  • An Eclipse workspace is organised like this:

    IWorkspaceRoot
     - IProject
       - mixture of IFolder and IFile
     - IProject
       - mixture of IFolder and IFile
     - ... more IProjects
    

    IFolder in turn can contain a mixture of more IFolder and IFile resources.

    IWorkspaceRoot, IProject, and IFolder all extend IContainer. IContainer and IFile extend IResource.

    The IResource.getProject method always returns the top IProject resource (except for IWorkspaceRoot).

    IResource.getParent returns the immediate IContainer parent (null for IWorkspaceRoot)

    So if you want the parent container of a resource call IResource.getParent, if you want the top level containing project call IResource.getProject.