【问题标题】:Programmaitcally adding nature to existing project以编程方式为现有项目添加自然
【发布时间】:2014-11-13 19:48:25
【问题描述】:

当我调整正在运行的项目的项目性质时

WorkspaceJob job = new WorkspaceJob("AddingNature") {

        @Override
        public IStatus runInWorkspace(IProgressMonitor monitor)
                throws CoreException {
try {

       IProjectDescription description = activeProject
                        .getDescription();
       String[] prevNatures = description.getNatureIds();
       String[] newNatures = new String[prevNatures.length + 1];
       System.arraycopy(prevNatures, 0, newNatures, 0,
            prevNatures.length);
       newNatures[prevNatures.length] = ID;

       description.setNatureIds(newNatures);
       activeProject.setDescription(description,
          new NullProgressMonitor());
       return Status.OK_STATUS;
   } catch (CoreException e) {
       LOGGER.log(Level.SEVERE, WARNING_NATURE_FAIL, e.getMessage());          
       return Status.CANCEL_STATUS;
    }  
}
job.schedule()

我收到一个错误 " 资源树已锁定以进行修改。" 异常堆栈跟踪不可用。

我认为调度应该避免资源树被锁定。 我能做些什么来防止这种情况发生?,有没有其他方法来添加性质/转换项目

使用扩展 AbstractHandler 的类从菜单项调用此代码。

【问题讨论】:

  • 可能是由使用 WorkspaceJob 引起的,我没有看到其他任何操作。大多数事情都使用 IRunnableWithProgress。

标签: java eclipse plugins


【解决方案1】:

数组String[] newNatures的大小问题。

试试这个:

public static void addProjectNature(IProject project, String natureID, boolean addFirst) {
    try {
        IProjectDescription description = project.getDescription();
        if (description.hasNature(natureID)) {
            return;
        }
        String[] natures = description.getNatureIds();
        String[] newNatures = new String[natures.length + 1];

        if (addFirst) {
            System.arraycopy(natures, 0, newNatures, 1, natures.length);
            newNatures[0] = natureID;
        } else {
            System.arraycopy(natures, 0, newNatures, 0, natures.length);
            newNatures[natures.length] = natureID;
        }
        IStatus status = project.getWorkspace().validateNatureSet(newNatures);
        if (status.getCode() == IStatus.OK) {
            description.setNatureIds(newNatures);
            project.setDescription(description, null);
        } else {
            //Error message
        }
    } catch (CoreException e) {
         e.printStackTrace();
    }
}

【讨论】:

  • 嗨,这很好。但是,当我尝试一些东西时,我粘贴了代码,“new String [natures.length + 1];”在我的代码中。我在原始帖子中编辑了我的代码。顺便说一句,如果我将 prevnatures 放回描述中,则没有错误
  • 检查 .log 文件是否存在 .metadata 文件夹中的任何错误并更新帖子。新的自然身份证也是有效的吗?在外部文本编辑器中打开 .project 文件并运行代码以检查外部编辑器是否提示您重新加载内容。
猜你喜欢
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
  • 2011-06-16
  • 2023-03-04
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 2011-07-19
相关资源
最近更新 更多