Eclipse本身并没有“选中的project”的概念,我们通常讲的“选中的project”通常是指Project Explorer中选中的资源所在的project,或者是指Editor Area中当前选中的文件所在的project。
1)获取Project Explorer中选中的资源所在的project代码如下。
IProject activeProject = null;
IWorkbenchWindow window = MyPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
ISelectionService selectionService = window.getSelectionService();
ISelection selection = selectionService.getSelection(IPageLayout.ID_PROJECT_EXPLORER);
if (selection instanceof StructuredSelection) {
IResource resource = (IResource) ((StructuredSelection) selection).getFirstElement();
activeProject = resource.getProject();
}
2)获取Editor Area中当前选中的文件所在的project
IProject activeProject = null;
IWorkbenchWindow window = MyPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
IEditorPart editorPart = window.getActivePage().getActiveEditor();
if (editorPart != null) {
IEditorInput input = (IEditorInput) editorPart.getEditorInput();
if (input instanceof IFileEditorInput) {
IFile file = ((IFileEditorInput) input).getFile();
activeProject = file.getProject();
}
}
其中MyPlugin为您当前开发Eclipse插件的Activator。
以上代码在Eclipse 4.2上测试通过。