在Eclipse插件中获取当前项目的通用方法

Tha*_*han 2 java eclipse-plugin

我正在创建一个eclipse插件,该插件应处理Project Explorer中所有打开的项目。它将在所选项目中创建一个文件。

我正在使用波纹管逻辑来获取当前项目。

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;
}
Run Code Online (Sandbox Code Playgroud)

这在开发人员模式下工作。但是在我导出为插件并安装后,发生了以下错误。

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

由于选择集中,选择似乎已切换到编辑器。有没有通用的方法来获取当前项目?

gre*_*449 8

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();
      }
   }
}
Run Code Online (Sandbox Code Playgroud)