Cannot cast eclipse project to IJavaProject

ⅰ亾dé卋堺 提交于 2019-12-01 15:59:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6642704/cannot-cast-eclipse-project-to-ijavaproject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!