以编程方式向现有项目添加性质

问题描述 投票:0回答:1

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

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 的类从菜单项调用的。

java eclipse plugins
1个回答
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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.