How to find the type of a selected member in Eclip

2019-07-28 06:48发布

问题:

I am co-developing an Eclipse plugin where Users can select Classes and Methods from their code and attach them to notes that are saved in a different file.

I want to find a way to determine what type of member was selected by the user when they choose to create an attachment.

For example:

I want to attach a class named "HelloClass" to a note called "HelloNote". I select the "HelloClass" member name in the editor, right-click and select my "Create Attachment" action. This action calls the "createAttachment" method, which already contains all the functionality for creating this attachment between the Class and the Note. However, I need to know whether the attached member is a Class or a Method. This information is neccessary, because if a Method is attached, I want to show the class it belongs to on the Note Attachment TreeView that my plugin offers.

My first instinct was using the Java Parser library to parse the entire file and look for the matching member name, but this can result in other problems (for example, two classes in the same file that share a method name in common). Eclipse itself already has some way of walking the AST (for example the Outline view). Is there an easier way to get this data?

回答1:

You basically want to do what org.eclipse.jdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getJavaElementsAt(ITextViewer, IRegion) does, specifically to get to the point where you can call org.eclipse.jdt.core.ICodeAssist#codeSelect(int, int) and determine to which elements the selected text refers (from 0 to n, the interface type in the returned array also indicating what kind of language element it is).