以编程方式为现有项目添加自然

时间:2014-11-13 10:20:01

标签: java eclipse plugins

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

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的类从menuitem调用此代码。

1 个答案:

答案 0 :(得分:0)

数组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();
    }
}