Search code examples
javaeclipse-cdtinstanceof

Java: instanceof returning false on Eclipse CDT IncludeRefContainer class


I have the following code:

private static IProject getProjectFromActivePart(IWorkbenchWindow activeWindow, ISelection selection) {
    if (selection != null && selection instanceof IStructuredSelection) {
        Object element = ((IStructuredSelection) selection).getFirstElement();
        if (element != null) {
            if (element instanceof IncludeRefContainer) {
                IncludeRefContainer cont = (IncludeRefContainer) element;
                return cont.getCProject().getProject();
            }
        }
    }
    return null;
}

the statment if(element instanceof IncludeRefContainer) returns false, even though element.getClass() returns:

class org.eclipse.cdt.internal.ui.cview.IncludeRefContainer

. Trying to cast the element object to IncludeRefContainer throws an exeption:

java.lang.ClassCastException: org.eclipse.cdt.internal.ui.cview.IncludeRefContainer cannot be cast to org.eclipse.cdt.internal.ui.cview.IncludeRefContainer

sounds very strange to me. how do i solve this?


Solution

  • Thanks to comments I got, I managed to solve the issue: It happens when the class object of the element was loaded by a different class loader as the class loader that loaded the class who tries to perform the cast. To fix it, I added the lib in the Dependencies->Imported Packages section instead of in the Runtime->ClassPath