簡體   English   中英

以編程方式為現有項目增加性質

[英]Programmaitcally adding nature to existing project

當我調整正在運行的項目的項目性質時

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的類從菜單項中調用此代碼。

數組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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM