Eclipse 에서 Context Menu 등을 사용할 때에 현재 Selection 한 객체가 어떤종류의 객체인지(IEditor 인지, IResource 인지) 판별을 해야 할 경우가 있다.


이때 주로 selection 의 instanceof 로 보고 확인하는데, 현재 선택한 Selection 정보를 보통 다음과 같이 가져온다.

IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ISelection selection = window.getSelectionService().getSelection();

if ( selection instanceof ITreeSelection ) {
    ...code...
} else if ( selection instanceof ITextSelection ) {
    ...code...
}

ISelection 은 다음과 같이 정의되어 있다.



위의 정의를 참고하여, 현재 Selection 한 객체가 Package Explorer 에서 Selection 한것인지 확인하려면 ITreeSection 이나 IStructuredSelection 으로 확인하고,

if ( selection instanceof ITreeSelection ) {
    // selected object in a tree view
    ...code...
}


Editor 에서 Selection 한것인지 확인하려면 ITextSelection 으로 확인하면 된다.

if ( selection instanceof ITextSelection ) {
    // selected text in a editor
    ...code...
}


Posted by leechwin
,