【转】http://wiki.eclipse.org/FAQ_How_do_I_access_the_active_project%3F
作为新手,好多人会问:如果获取Active Project、Active File、and active folder。事实上,在eclipse中不存在“Active”Project 和File;只有当前的(currently)project和file。
那么如果获取呢?下面介绍常用的方式:
1.通过UI的ISelectionService获取project、file、folder
一但你获取了一个selection,你就可以获取选择的resource
IResource extractSelection(ISelection sel) {
if (!(sel instanceof IStructuredSelection))
return null;
IStructuredSelection ss = (IStructuredSelection) sel;
Object element = ss.getFirstElement();
if (element instanceof IResource)
return (IResource) element;
if (!(element instanceof IAdaptable))
return null;
IAdaptable adaptable = (IAdaptable)element;
Object adapter = adaptable.getAdapter(IResource.class);
return (IResource) adapter;
}
2.通过IPartService获取resource
IResource extractResource(IEditorPart editor) {
IEditorInput input = editor.getInput();
if (!(input instanceof IFileEditorInput))
return null;
return ((IFileEditorInput)input).getFile();
}
3.IResource.getProject()
题外话,对于project、file等resource,我们通常说“selected”;对于编辑器、视图,我们通常说“Active”
IWorkbench iworkbench = PlatformUI.getWorkbench();
if (iworkbench == null)...
IWorkbenchWindow iworkbenchwindow = iworkbench.getActiveWorkbenchWindow();
if (iworkbenchwindow == null) ...
IWorkbenchPage iworkbenchpage = iworkbenchwindow.getActivePage();
if (iworkbenchpage == null) ...
IEditorPart ieditorpart = iworkbenchpage.getActiveEditor();
IStructuredSelection
ITextSelection
IWorkbench iworkbench = PlatformUI.getWorkbench();
if (iworkbench == null)...
IWorkbenchWindow iworkbenchwindow = iworkbench.getActiveWorkbenchWindow();
if (iworkbenchwindow == null) ...
IWorkbenchPage iworkbenchpage = iworkbenchwindow.getActivePage();
if (iworkbenchpage == null) ...
IEditorPart ieditorpart = iworkbenchpage.getActiveEditor();