Skip to main content
Jump to: navigation, search

FAQ How do I access the active project?

Revision as of 02:05, 3 October 2006 by (Talk | contribs) (See Also:)

This question is often asked by newcomers to Eclipse, probably as a result of switching from another IDE with a different interpretation of the term project. Similarly, people often ask how to access the “active” file. In Eclipse there is no such thing as an active project or file. Projects can be opened or closed, but many projects may be open at any given time.

Often people are really asking for the currently selected project, folder, or file. The selection can be queried using the UI’s ISelectionService.

Once you have the selection, you can extract the selected resource as follows:

   IResource extractSelection(ISelection sel) {
      if (!(sel instanceof IStructuredSelection))
         return null;
      IStructuredSelection ss = (IStructuredSelection) sel;
      Object element = ss.getFirstElement();
      if (element instanceof IResource)
         return (IResource) element;
      if (!(element instanceof IAdaptable))
         return null;
      IAdaptable adaptable = (IAdaptable)element;
      Object adapter = adaptable.getAdapter(IResource.class);
      return (IResource) adapter;

If you are looking for the active editor, you can determine that from the IPartService. If an editor is active, you can extract the resource, if available, like this:

   IResource extractResource(IEditorPart editor) {
      IEditorInput input = editor.getInput();
      if (!(input instanceof IFileEditorInput))
         return null;
      return ((IFileEditorInput)input).getFile();

The code above has a minor error:

IEditorInput input = editor.getEditorInput();

See Also:

This FAQ was originally published in Official Eclipse 3.0 FAQs. Copyright 2004, Pearson Education, Inc. All rights reserved. This text is made available here under the terms of the Eclipse Public License v1.0.

Back to the top