从自定义 IStorage 实现中获取 IProject

Get IProject from a custom IStorage implementation

我目前正在开发 Eclipse Neon 编辑器插件。目前我正试图从文件系统中打开文件,这些文件不是在 Eclipse 中创建的。为此,我需要通过以下方法获得 IProject

public static IProject getProject(IStorage storage) {
    if (storage instanceof IFile) {
      return ((IFile) storage).getProject();
    }
    else if (storage instanceof IJarEntryResource) {
      return ((IJarEntryResource) storage).getPackageFragmentRoot().getJavaProject().getProject();
    }
    else if (storage instanceof FileStorage) {
      // ????
    }
    else {
      throw new IllegalArgumentException("Unknown IStorage implementation");
    }
  }

此处FileStorageIStorage接口的自己实现。看起来像这样:

public class FileStorage implements IStorage {
  private final FileStoreEditorInput editorInput;

  FileStorage( FileStoreEditorInput editorInput ) {
    this.editorInput = editorInput;
  }

  @Override
  public <T> T getAdapter( Class<T> adapter ) {
    return Platform.getAdapterManager().getAdapter( this, adapter );
  }

  @Override
  public boolean isReadOnly() {
    return false;
  }

  @Override
  public String getName() {
    return editorInput.getName();
  }

  @Override
  public IPath getFullPath() {
    return new Path( URIUtil.toFile( editorInput.getURI() ).getAbsolutePath() );
  }

  @Override
  public InputStream getContents() {
    try {
      return editorInput.getURI().toURL().openStream();
    } catch( IOException e ) {
      throw new UncheckedIOException( e );
    }
  }
}

有没有办法从这个 FileStorage 得到一个 IProject

简而言之:不。FileStorage class 用于表示位于工作空间 外部 的文件的 IStorage 个实例.因此它们不包含在任何工作区项目中,并且不可能为它们获得 IProject

您可以尝试使用以下方法获取文件的 IFile

IPath path = ... absolute path to the file

IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IFile file = root.getFileForLocation(path);
if (file != null) {
  IProject project = file.getProject();
  ...
}

但这只适用于工作区内的文件。对于工作区之外的任何内容,您都无法拥有项目。