2013-06-19 85 views
1

我正在嘗試編寫一個eclipse插件,在那裏我必須找到當前所選項目的路徑
項目。一個重要的事情是,這是一個C或C++項目,而不是我必須選擇的Java項目。我試了一些代碼 -如何在eclipse插件中找到當前選中項目的路徑

 File currDir = new File("."); 
     String path = currDir.getAbsolutePath(); 
     path = path.substring(0, path.length()-1); 
     System.out.println(path); 

但是這一個給出了eclipse插件目錄不是當前項目的路徑。

 IWorkspace workspace = ResourcesPlugin.getWorkspace(); 
     IWorkspaceRoot root = workspace.getRoot(); 
     IProject[] projects = root.getProjects(); 
     for (IProject project : projects) { 
     try { 
      printProjectInfo(project);  
      } catch (CoreException e) { 
       e.printStackTrace(); 
      } 
     } 


     private void printPackageInfos(IJavaProject javaProject) 
     throws JavaModelException { 
      IPackageFragment[] packages = javaProject.getPackageFragments(); 
      for (IPackageFragment mypackage : packages) { 

       if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) 
        {     
         printICompilationUnitInfo(mypackage); 
        } 
       } 
       } 

但是這只是選擇java項目。

那麼,有沒有辦法做到這一點.....

回答

8
public static IProject getCurrentProject(){  
     ISelectionService selectionService =  
      Workbench.getInstance().getActiveWorkbenchWindow().getSelectionService();  

     ISelection selection = selectionService.getSelection();  

     IProject project = null;  
     if(selection instanceof IStructuredSelection) {  
      Object element = ((IStructuredSelection)selection).getFirstElement();  

      if (element instanceof IResource) {  
       project= ((IResource)element).getProject();  
      } else if (element instanceof PackageFragmentRootContainer) {  
       IJavaProject jProject =  
        ((PackageFragmentRootContainer)element).getJavaProject();  
       project = jProject.getProject();  
      } else if (element instanceof IJavaElement) {  
       IJavaProject jProject= ((IJavaElement)element).getJavaProject();  
       project = jProject.getProject();  
      }  
     }  
     return project;  
    } 

希望工程:-)

+0

謝謝Sam先生,對我來說PackageFragmentRootContainer不工作,我用PackageFragmentRoot。它給了我所選項目的名字,但我正在尋找該項目的絕對路徑。有沒有辦法... – DEV

相關問題