かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

選択されたリソースの所属するプロジェクトを取得するには

org.eclipse.core.resourcesを依存関係に追加して以下のコードでとれる。

package org.okazuki.helloworld.actions;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

public class ProjectAction implements IWorkbenchWindowActionDelegate {

	private IWorkbenchWindow window;
	private IStructuredSelection selection;
	
	public void dispose() {

	}

	public void init(IWorkbenchWindow window) {
		this.window = window;
	}

	public void run(IAction action) {
		if (selection == null) {
			return;
		}
		print(selection.getFirstElement().getClass());
		if (selection.getFirstElement() instanceof IResource) {
			IResource resource = (IResource) selection.getFirstElement();
			IProject project = resource.getProject();
			MessageDialog.openConfirm(window.getShell(), "Project", project.getName());
		}
	}
	
	private void print(Class clazz) {
		for (Class c : clazz.getInterfaces()) {
			System.out.println(c);
			print(c);
		}
	}

	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			this.selection = (IStructuredSelection) selection;
		} else {
			this.selection = null;
		}
	}

}

ただ、これだとNavigator上でじゃないとうまく動かない。
Package Explorer上だと駄目だから、もう一工夫かな。