Search code examples
eclipsepluginseclipse-jdt

How get the path of a java file selected in the pacake explorer in eclipse


I have this code in an Eclipse plugin. I need to get the path of whatever file. For instances of IFile it works, but for ICompilationUnit I have no idea.

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;
    }
}

Solution

  • Use:

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