I am working with the selections within the Eclipse source code editor. I defined a key-binding that gets me the “text” at the current caret position. I managed to parse the current caret position to an IJavaElement
private void processEditorSelection(IEditorPart part, ITextSelection selection) {
IEditorInput editorInput = ((IEditorPart) part).getEditorInput();
final ITypeRoot root = (ITypeRoot) JavaUI.getEditorInputJavaElement(editorInput);
if (root != null) {
int offset = (selection).getOffset();
IJavaElement[] codeSelect = root.codeSelect(offset, 0);
if (codeSelect.length > 0) {
//codeSelect[0...n] are my resolved elements at the current caret pos.
}
What I did not managed to figure out yet is, how to resolve the enclosing type. for instance:
public void do() {
System.out.println("it");
}
If the caret is on the System.out, I obtain an JavaElement of the system out call, but I am actually interested in the enclosing method. Does anyone know how to ask Eclipse for the enclosing type? Like what is the compilation unit or method my current carret position is enclosed in?
Thanks for an answer
You are looking to do something like this:
This will find the enclosing element, which may be an
IField,IMethod, orICompilationUnit. To get the enclosing type, call this:This method returns null if there is no enclosing type.