How to get a project when right-clicking on a project / file / other in eclipse-plugin

I am writing a simple eclipse plugin, but I have a problem: when a user right-clicks on a node (possibly a project, file, java compilation unit or others), I want to get the project it belongs to.

Code example:

public class MyAction implements IObjectActionDelegate { private IProject project; public void selectionChanged(IAction action, ISelection selection) { this.project = getSelectedProject(selection); } public static IProject getSelectedProject(Object obj) throws Exception { if (obj == null) { return null; } if (obj instanceof IResource) { return ((IResource) obj).getProject(); } else if (obj instanceof IStructuredSelection) { return getSelectedProject(((IStructuredSelection) obj).getFirstElement()); } return null; } } 

It works in most cases, but sometimes, for example, I right-click on a java file, the choice will be ICompilationUnit . Although I can add more if to getSelectedProject , but I don't think this is a good idea.

Is there a way to get the project of the selected object that was selected? I do not want to add them one by one.

+4
source share
3 answers

ICompilationUnit extends IAdaptable (see http://publib.boulder.ibm.com/infocenter/rsmhelp/v7r0m0/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt /core/ICompilationUnit.html )

You can try and use the IAdaptable interface as follows:

 if (obj instanceof IAdaptable) { IResource res = (IResource)(((IAdaptable)obj).getAdapter(IResource.class)); if (res != null) { return res.getProject(); } } 
+2
source

Unable to convert ICompilationUnit , IPackage , etc. in IResource , as most often there is no corresponding resource! For instance. for .class elements in the navigator, the element corresponds to an entry in the JAR file or the dependency plug-in from the target platform.

0
source

This answer does not work, maybe:

  if (obj instanceof IStructuredSelection) { IStructuredSelection selection1 = (IStructuredSelection)obj; Object element = selection1.getFirstElement(); IProject project = null; if (element instanceof IProject) { project = (IProject) element; } else if (element instanceof IAdaptable) { project = (IProject) ((IAdaptable) element).getAdapter(IProject.class); } if (project != null) { return project; } } 
0
source

All Articles