我正在尝试编写一个eclipse插件,我必须找到当前所选的路径 项目。一个重要的事情是,这是一个C或C ++项目,而不是我必须选择的java项目。我尝试了一些代码 -
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length()-1);
System.out.println(path);
但是这个给出了eclipse插件目录的路径而不是当前的项目。
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject[] projects = root.getProjects();
for (IProject project : projects) {
try {
printProjectInfo(project);
} catch (CoreException e) {
e.printStackTrace();
}
}
private void printPackageInfos(IJavaProject javaProject)
throws JavaModelException {
IPackageFragment[] packages = javaProject.getPackageFragments();
for (IPackageFragment mypackage : packages) {
if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE)
{
printICompilationUnitInfo(mypackage);
}
}
}
但是这个只选择java项目。
有没有办法做到这一点......
答案 0 :(得分:8)
public static IProject getCurrentProject(){
ISelectionService selectionService =
Workbench.getInstance().getActiveWorkbenchWindow().getSelectionService();
ISelection selection = selectionService.getSelection();
IProject project = null;
if(selection instanceof IStructuredSelection) {
Object element = ((IStructuredSelection)selection).getFirstElement();
if (element instanceof IResource) {
project= ((IResource)element).getProject();
} else if (element instanceof PackageFragmentRootContainer) {
IJavaProject jProject =
((PackageFragmentRootContainer)element).getJavaProject();
project = jProject.getProject();
} else if (element instanceof IJavaElement) {
IJavaProject jProject= ((IJavaElement)element).getJavaProject();
project = jProject.getProject();
}
}
return project;
}
希望它有效: - )