Universal way to get the current project in eclipse plugin

Viewed 2902

I am creating an eclipse plugin which should deal with all opened projects inside Project explorer. It will create an file inside the selected project.

I am using the bellow logic to get the current project.

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;
}

This is working in the developer mode. But after I export as a plugin and install, the following error occurred.

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

It looks like selection has switched to editor since it has been focused. Is there any universal way to get the current project?

1 Answers
Related