javaeclipse-plugineclipse-rcpeclipse-gmf

How to get the project name in eclipse?


How do I get the name of the current eclipse project? I'm in a GMF view and need the projectname when some submenu of the popup menu ist used.


Solution

  • This GMF class has a straightforward answer, if you have access to the ResourcesPlugin name:

    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(myBundleName);
    

    The generic answer (from a potentially outdated code) could be like (if you have an editor opened):

    IEditorPart  editorPart =
    getSite().getWorkbenchWindow().getActivePage().getActiveEditor();
    
    if(editorPart  != null)
    {
        IFileEditorInput input = (IFileEditorInput)editorPart.getEditorInput() ;
        IFile file = input.getFile();
        IProject activeProject = file.getProject();
        String activeProjectName = activeProject.getName();
        //... use activeProjectName 
    }
    

    If no editor is opened:

       IViewPart [] parts =
          MyPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().getViews();
        IProject activeProject = null;
    
        for(int i=0;i<parts.length;i++)
        {
            if(parts[i] instanceof ResourceNavigator)
            {
                ResourceNavigator navigator = (ResourceNavigator)parts[i];
                StructuredSelection sel   =
                  (StructuredSelection)navigator.getTreeViewer().getSelection();
                IResource resource = (IResource)sel.getFirstElement();
                activeProject = resource.getProject();
                break;
            }
        }
        String activeProjectName = activeProject .getName();