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?
Eclipse doesn't have a concept of 'current project'. The selection service gives you the selection for the currently active part which may be an editor or a view.
If the selection you get back from ISelectionService.getSelection
is not an IStructuredSelection
then the active part is probably an editor. So in that case you can try and get the current project from the active editor using something like:
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With