Eclipse Plugin:如何获取当前选中项目的路径

2022-01-16 00:00:00 eclipse-plugin java eclipse eclipse-pde

我正在编写一个 Eclipse 插件,它将在 Java 项目的上下文菜单中显示一个菜单项.我将plugin.xml写成如下:

I am writing an Eclipse plugin that will display a menu item in the context menu for a Java Project. I have written the plugin.xml as follows:

<plugin>
   <extension
         point="org.eclipse.ui.menus">
      <menuContribution
            locationURI="popup:org.eclipse.jdt.ui.PackageExplorer">
         <dynamic
               class="uk.co.dajohnston.plugin.classpathswitcher.menu.MenuContribution"
               id="uk.co.dajohnston.plugin.classpathSwitcher.switchMenuContribution">
            <visibleWhen>
               <with
                     variable="activeMenuSelection">
                  <iterate>
                     <adapt
                           type="org.eclipse.jdt.core.IJavaProject">
                     </adapt>
                  </iterate>
                  <count
                        value="1">
                  </count>
               </with>
            </visibleWhen>
         </dynamic>
      </menuContribution>
   </extension>

</plugin>

所以我现在正在尝试编写扩展 CompoundContributionItemMenuContribution 类,以便我可以创建动态菜单,并且该菜单的内容将基于Java 项目的根目录中存在的一组文件.但我一直试图从 getContributionItems 方法中获取根目录的路径.

So I am now trying to write the MenuContribution class which extends CompoundContributionItem so that I can create a dynamic menu and the contents of this menu are going to be based on a set of files that exist in the Java Project's root directory. But I am stuck trying to get the path to the root directory from within the getContributionItems method.

基于 plugin.xml 文件,我可以保证只有在选择了单个 Java 项目时才会调用该方法,所以我需要做的就是获取当前选择,然后获取其绝对路径.有任何想法吗?或者有更好的方法吗?

Based on the plugin.xml file I can be guarenteed that the method will only be called if a single Java Project is selected, so all I need to do is get the current selection and then get its absolute path. Any ideas? Or is there a better way to do this?

推荐答案

这应该让你更接近(如果不能为你完全解决它;))

This should get you closer (if not solve it completely for you ;))

    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window != null)
    {
        IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection();
        Object firstElement = selection.getFirstElement();
        if (firstElement instanceof IAdaptable)
        {
            IProject project = (IProject)((IAdaptable)firstElement).getAdapter(IProject.class);
            IPath path = project.getFullPath();
            System.out.println(path);
        }
    }

相关文章