Get name of enclosing java method based on caret location
I have an action in "EditorPopupMenu" group. When a java file is open in the editor and user triggers this action through a keyboard shortcut, i am able to get the caret logical position and also enclosing java file. Whats the best way to get the enclosing java method name based on the caret position
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
//Get all the required data from data keys
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
final Document document = editor.getDocument();
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile instanceof PsiJavaFile) {
System.out.println("found java file");
PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;
}
}
Please sign in to leave a comment.
Hi,
if you don't want to work with multiple carets, then the code should look like something like this:
{code}
caret = editor.getCaretModel().getOffset();
method = PsiTreeUtil.getParentOfType(file.findElementAt(caret), PsiMethod.class);
if (method != null) method.getName()
{code}
Anna