Search code examples
javaeclipsecastingeclipse-plugininstanceof

Can't cast or instanceof to true from Object to IProject || Java Eclipse Plugin-Development


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

Solution

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