2017-05-24 57 views
2

我正在創建一個eclipse插件,它應該處理Project Explorer中所有打開的項目。它將在選定的項目中創建一個文件。在eclipse插件中獲取當前項目的通用方法

我正在使用波紋管邏輯來獲取當前項目。

public IProject getCurrentProject() { 
    IProject project = null; 
    IWorkbenchWindow window = PlatformUI.getWorkbench() 
      .getActiveWorkbenchWindow(); 
    if (window != null) { 
     ISelection iselection = window.getSelectionService().getSelection(); 
     IStructuredSelection selection = (IStructuredSelection) iselection; 
     if (selection == null) { 
      return null; 
     } 

     Object firstElement = selection.getFirstElement(); 
     if (firstElement instanceof IResource) { 
      project = ((IResource) firstElement).getProject(); 
     } else if (firstElement instanceof PackageFragmentRoot) { 
      IJavaProject jProject = ((PackageFragmentRoot) firstElement) 
        .getJavaProject(); 
      project = jProject.getProject(); 
     } else if (firstElement instanceof IJavaElement) { 
      IJavaProject jProject = ((IJavaElement) firstElement) 
        .getJavaProject(); 
      project = jProject.getProject(); 
     } 
    } 
    return project; 
} 

這是在開發人員模式下使用。但是在我作爲插件導出並安裝之後,發生了以下錯誤。

org.eclipse.e4.core.di.InjectionException: java.lang.ClassCastException: org.eclipse.jface.text.TextSelection cannot be cast to org.eclipse.jface.viewers.IStructuredSelection

它看起來像既然已經選擇的重點已切換到編輯器。 有沒有什麼通用的方法來獲得當前的項目?

回答

4

Eclipse沒有「當前項目」的概念。選擇服務爲您提供當前活動部分的選擇,這可能是編輯器或視圖。

如果您從ISelectionService.getSelection得到的選擇不是IStructuredSelection,那麼活動部分可能是一個編輯器。所以在這種情況下,你可以嘗試從活動編輯器中獲取當前項目,例如:

IWorkbenchPage activePage = window.getActivePage(); 

IEditorPart activeEditor = activePage.getActiveEditor(); 

if (activeEditor != null) { 
    IEditorInput input = activeEditor.getEditorInput(); 

    IProject project = input.getAdapter(IProject.class); 
    if (project == null) { 
     IResource resource = input.getAdapter(IResource.class); 
     if (resource != null) { 
     project = resource.getProject(); 
     } 
    } 
} 
+0

完美地工作! @greg,你總是救我! –

相關問題