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.
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.