Question

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;
    }
}
Was it helpful?

Solution

Use:

IResource resource = (IResource)Platform.getAdapterManager().getAdapter(firstElement, IResource.class);

if (resource != null) {
    IPath path = resource.getLocation();

    ...
}

OTHER TIPS

Try checking if firstElement is a CompilationUnit, not an ICompilationUnit, as it is the only one implementation of ICompilationUnit. Than you can call getCorrespondingResource() method.

You can use:

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

This will give you the entire path for the selected ICompilationUnit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top