How to get virtual file of a reference

Support class A has a reference of class B:

B myObject = new B();

My current editor shows class A. Hence, i can get psiClass of class A from AnActionEvent. Is there a way to get the virtual file of class B?

0
4 comments

You can find B by name (com.intellij.psi.JavaPsiFacade#findClass) and then call com.intellij.psi.util.PsiUtilCore#getVirtualFile passing found class there. Or you may resolve reference on class B instead of finding by name but then you need to have caret on B.

Anna

0
Avatar
Permanently deleted user

Hi Anna,

 

To use com.intellij.psi.JavaPsiFacade#findClass, I need to pass the QualifiedName of class B. Is there a way to get it? (The caret is currently on class A, and I get the name of Class B by selectionModel.getSelectedText(). )

0
Avatar
Permanently deleted user

What I found is to use in this way:

String selectedText = selectionModel.getSelectedText(); // selectedText is the name of Class B
PsiElement elementAt = psiFile.findElementAt(selectionModel.getSelectionStart());
PsiElement original = elementAt.getOriginalElement();
String qualifiedName = original.getContext().getReference().getCanonicalText();

Is this a correct way?

0

The better way to get B if you have editor with caret on B is to call com.intellij.codeInsight.TargetElementUtil#findTargetElement(com.intellij.openapi.editor.Editor, int). BTW editor.getCaretModel().getCaret() would give you caret position when no selection is available.

Hope this helps,

Anna 

0

Please sign in to leave a comment.