我是Eclipse插件开发的新手,所以我需要一些帮助。 我有一个项目,我必须在活动编辑器中获取光标的当前位置,并在单击按钮时,我将在对话框中显示直接围绕它的方法。我尝试了以下内容,到目前为止我只能获取方法的名称,但不能获得我想要的整个源代码。如果我只尝试使用compilationUnit,我也可以获得活动编辑器的完整源代码。其他问题似乎只需要方法的名称,但我有兴趣获取该方法的完整源代码。有什么办法可以直接获取光标周围方法的源代码吗?
IWorkbenchPage page = window.getActivePage();
IEditorPart editor = page.getActiveEditor();
ITextEditor textEditor = (ITextEditor) page.getActiveEditor();
IJavaElement element = JavaUI.getEditorInputJavaElement(textEditor.getEditorInput());
if (element instanceof ICompilationUnit) {
ITextSelection selection = (ITextSelection) ((JavaEditor) textEditor).getSelectionProvider().getSelection();
IJavaElement selected;
try {
selected = ((ICompilationUnit) element).getElementAt(selection.getOffset());
if (selected != null && selected.getElementType() == IJavaElement.METHOD) {
return (IMethod) selected;
}
MessageDialog.openInformation(
window.getShell(),
editor.getTitle(),
selected +"\n"); //(IMethod)
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:0)
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
try {
IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ISelection selection = workbenchWindow.getSelectionService().getSelection();
ITextSelection textSelection;
if (selection instanceof ITextSelection)
textSelection = (ITextSelection) selection;
else
throw new RuntimeException("No text selection");
IEditorInput editorInput = workbenchWindow.getActivePage().getActiveEditor().getEditorInput();
ICompilationUnit compilationUnit = JavaUI.getWorkingCopyManager().getWorkingCopy(editorInput);
IJavaElement elementWithCursorInside = compilationUnit.getElementAt(textSelection.getOffset());
ISourceReference sourceReference;
if (elementWithCursorInside instanceof ISourceReference)
sourceReference = (ISourceReference) elementWithCursorInside;
else
throw new RuntimeException("Not an ISourceReference");
MessageDialog.openInformation(window.getShell(), "Source Code of the Method", sourceReference.getSource());
} catch (Exception e) {
e.printStackTrace();
}
return null;
这对我来说似乎很有用。我希望也许我的解决方案可以帮助其他人解决同样的问题