Cannot cast eclipse project to IJavaProject
Asked Answered
E

1

9

I have the following code

    IJavaProject targetProject = null;
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    for (IProject project : root.getProjects()) {
        if (project.getName().equals(projName)) {
            try {
                if (project.hasNature("org.eclipse.jdt.core.javanature")) {
                    targetProject = (IJavaProject) project;
                }
            } catch( ... ) {
             // etc ...
            }

What I am trying to do is essentially return a project that matches a particular name as an IJavaProject. As you can see, I check to ensure that the project in question has a java nature by calling:

if (project.hasNature("org.eclipse.jdt.core.javanature")) {

Alas, I get a 'ClassCaseException' stating

java.lang.ClassCastException: 
    org.eclipse.core.internal.resources.Project cannot be cast to org.eclipse.jdt.core.IJavaProject

Any idea why? I would have thought that once an IProject has a java nature, it can be cast to a IJavaProject. I can't get access to the JDT Core API at the moment as the service is unavailable here.

Emmi answered 10/7, 2011 at 17:39 Comment(0)
M
22

The code in your answer shouldn't work (typo?). Here is how you can create an IJavaProject:

import org.eclipse.jdt.core.JavaCore
...
    if (project.hasNature(JavaCore.NATURE_ID)) {
        targetProject = JavaCore.create(project);
    }

IProject is a type in the Eclipse Resources API and IJavaProject is a type in the Eclipse Java Model. They are not the same abstractions, but all IJavaProjects have an IProject.

Multitudinous answered 11/7, 2011 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.