I’m currently working on an Eclipse addon which would help me coding. Basically a library of String snippets.
When creating a new one, I’d love to give it an ID of sorts ClassName.MethodName.X.
Getting the editor is pretty straightforward:
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
IEditorPart activeEditor = page.getActiveEditor();
if(activeEditor.getClass().getName().endsWith("CompilationUnitEditor")){
// do something
}
Now… is there any way to use the Eclipse jdt APIs to get the name of the method my text cursor is currently in?
Edit:
Ok. With the help of Andrew, here’s what I got:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart activeEditor = page.getActiveEditor();
if(activeEditor instanceof JavaEditor) {
ICompilationUnit root = (ICompilationUnit) EditorUtility.getEditorInputJavaElement(activeEditor, false);
try {
ITextSelection sel = (ITextSelection) ((JavaEditor) activeEditor)
.getSelectionProvider().getSelection();
int offset = sel.getOffset();
IJavaElement element = root.getElementAt(offset);
if(element.getElementType() == IJavaElement.METHOD){
return element.getElementName());
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
Works pretty good. Although it’s kind of a dirty solution to use restricted classes.
Not sure if you are asking for the method surrounding the current caret location, or the method that the caret location is selecting. I’ll show you both.
First, surrounding method:
The important methods are
getElementAtandgetSelection.And here is how to find the method that is currently selected by the caret:
The interesting method here is
codeSelectwhich resolves the current selection in the context of the given compilation unit or class file.Actual code will be different since you need to check for null in many places, but you should not need to do any other instanceof tests.