How to find the type of the selected item in Eclipse?

I am jointly developing an Eclipse plugin in which users can select classes and methods from their code and attach them to notes that are saved in another file.

I want to find a way to determine what type of element the user has selected when they want to create an attachment.

For instance:

I want to add a class called "HelloClass" to the "HelloNote" note. I select the member name "HelloClass" in the editor, right-click and select the action "Create Application". This action calls the createAttachment method, which already contains all the functions to create this attachment between the class and the record. However, I need to know if the attached element is a class or method. This information is necessary because if the method is attached, I want to show the class to which it belongs in the TreeView Note Note that my plugin offers.

My first instinct used the Java Parser library to parse the entire file and find a suitable member name, but this can lead to other problems (for example, two classes in the same file sharing the method name). Eclipse itself already has some way of walking around the AST (for example, the Outline view). Is there an easier way to get this data?

+1
source share
1 answer

Basically you want to do what org.eclipse.jdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getJavaElementsAt(ITextViewer, IRegion) , in particular, to go to the point where you can call org.eclipse.jdt.core.ICodeAssist#codeSelect(int, int) , and determine which elements the selected text belongs to (from 0 to n, the type of interface in the returned array also indicating which language this element is).

0
source

All Articles