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.