【问题标题】:How get the path of a java file selected in the pacake explorer in eclipse如何获取在eclipse中包资源管理器中选择的java文件的路径
【发布时间】:2013-09-24 14:30:17
【问题描述】:

我在 Eclipse 插件中有这段代码。我需要获取任何文件的路径。对于IFile 的实例,它可以工作,但对于ICompilationUnit,我不知道。

final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
final IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection("org.eclipse.jdt.ui.PackageExplorer");
    
final Object firstElement = selection.getFirstElement();
String selectedFile = "";
                
if (firstElement instanceof IFile){
    IPath loc = ((IFile) firstElement).getLocation();
    if (loc != null){
        selectedFile = loc.toOSString();
        if(!selectedFile.endsWith(".java")){
            selectedFile = "";
        }
    }
} else {
    if(firstElement instanceof ICompilationUnit){   
        CompilationUnit comUnit = ( CompilationUnit)firstElement;
    }
}

【问题讨论】:

    标签: eclipse plugins eclipse-jdt


    【解决方案1】:

    用途:

    IResource resource = (IResource)Platform.getAdapterManager().getAdapter(firstElement, IResource.class);
    
    if (resource != null) {
        IPath path = resource.getLocation();
    
        ...
    }
    

    【讨论】:

    • 而当资源不是IFile实例时,比如CompilationUnit?
    • 其实你只需要路径就可以使用IResource.getLocation。希望适配器管理器能够找到与编译单元匹配的IResource
    • 是的,适配器管理器应该能够从 CompilationUnit 转换为 IResource
    • 如果问题是关于 eclipse 并且 Greg 给出了答案 - 您无需进一步搜索 :-)
    【解决方案2】:

    尝试检查 firstElement 是否为CompilationUnit,而不是ICompilationUnit,因为它是ICompilationUnit 的唯一实现。比你可以调用getCorrespondingResource() 方法。

    【讨论】:

    • 现在无法访问eclipse帮助页面。我在 CompilationUnit 类中没有 getCorrecpondingResource() 方法。我需要哪个导入?
    【解决方案3】:

    你可以使用:

    String path = iCompilationUnit.getResource().getFullPath();
    

    这将为您提供所选ICompilationUnit 的完整路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多