0

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?

one
  • 511
  • 5
  • 17
  • Such a "strange" error message appears when this same class was loaded by two different class loaders. That means that the class object of your element was loaded by a different class loader as the class loader that loaded the class whose code you have shown. Unfortunately, I do not know enough of Eclipse internals to help you. Maybe you have multiple dependencies to the lib in question? – Seelenvirtuose May 12 '15 at 08:07
  • Check this question: http://stackoverflow.com/questions/826319/classcastexception-when-casting-to-the-same-class – Veselin Davidov May 12 '15 at 08:09

1 Answers1

0

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

one
  • 511
  • 5
  • 17