0

Why can I not cast the content from an Array of type Object, which an Eclipse framework method for getting the selection of the package explorer returns, to IProject? instanceof returns false and casting without check causes an exception. But the debugger shows the content of the Object[]-array to have all the instance-variables and everything of an IProject-type:

private List<IProject> getValidSelectedProjects(IWorkbenchWindow window) {
        final ISelectionService service = window.getSelectionService();
        final IStructuredSelection structured = (IStructuredSelection) service.getSelection("org.eclipse.jdt.ui.PackageExplorer");
        if (structured == null){
            return null;
        } else {
            final Object[] selectedProjects = structured.toArray();         
            ArrayList<IProject> validatedProjects = new ArrayList<IProject>();
            for (final Object projectObj : selectedProjects){
                 if (projectObj instanceof IProject){
                    IProject project = (IProject) projectObj;
                    //do something
                    }
 //rest of the method; returning list of validated projects

I also tried How to convert between an Object[] and an interface (IProject[]) in Java?

but there I get an Exception at this line:

System.arraycopy(objectarray, 0, projectarray, 0, objectarray.length);
Community
  • 1
  • 1
Phil
  • 7,065
  • 8
  • 49
  • 91

1 Answers1

1

User interface objects returned by getSelection() are usually not directly instances of IProject, IFile or IResource.

To get the IProject ... use the IAdapterManager:

IProject project = (IProject)Platform.getAdapterManager().getAdapter(projectObj, IProject.class);

Sometimes the object does not provide an adapter directly to IProject, so try the more general IResource:

IResource resource = (IResource)Platform.getAdapterManager().adapt(projectObj, IResource.class);

if (resource instanceof IProject)
 {
   IProject project = (IProject)resource;

   ... your code
 }
greg-449
  • 109,219
  • 232
  • 102
  • 145
  • Thank you for clarifying the problem. But why do I get the error "The method adapt(Object, Class) is undefined for the type IAdapterManager"? – Phil Oct 15 '14 at 12:34
  • Ok, thanks again. With getAdapter(...) instead of adapt(...) this park of code finally works. – Phil Oct 15 '14 at 12:55
  • Sorry, my fault for not checking method names. It is the Eclipse e4 `Adapter` class that uses `adapt` as the method name! – greg-449 Oct 15 '14 at 12:58