[Plugin][Code Intention] Get PsiType of Class to the left of user's cursor
TL;DR: Given the PsiElement passed to IntentionAction#isAvailable, how do I get PsiType for what *might* be a Class to the left of the user's cursor ?
Consider the following piece of code:
import com.fake.package.FooBar;
public void fakeMethod() {
FooBar|
}
Imagine that there is a class FooBar and the user's cursor is placed at the end of FooBar in the above code snippet (i.e. where I have placed | ). I am developing a Code Intention that requires I have a PsiType instance for FooBar (i.e. the class directly to the left of the user's cursor if it is indeed a class -- if it's not a class the Intention Action won't be available).
Where I am currently stuck is using the PsiElement given to IntentionAction#isAvailable(...) to get an instance of PsiType representing FooBar.
Here's what I've got so far (where elementAtCursor is the PsiElement passed to IntentionAction#isAvailable(..))
PsiElement elementLeftOfCursor = elementAtCursor.getPrevSibling();
PsiReferenceExpression referenceExpression =
(elementLeftOfCursor instanceof PsiReferenceExpression) ?
(PsiReferenceExpression) elementLeftOfCusor :
PsiTreeUtil.findChildOfType(elementLeftOfCursor, PsiReferenceExpression.class);
This gives me an instance of PsiReferenceExpression that points to FooBar but I'm unsure of how to go from that to PsiType for FooBar... I imagine I must use the Class' import statements somehow and match to this reference expression.
Any tips here? I can't seem to figure out how to use the class' import statements to retrieve the PsiType here.
请先登录再写评论。
You can call referenceExpression.resolve() to get instance of PsiClass it refers to, it'll automatically take import statements into account. Then you can invoke You can invoke PsiElementFactory#createType to create PsiType from PsiClass. Also you can invoke PsiElementFactory.SERVICE.getInstance().createType(referenceExpression) to create PsiType from PsiReferenceExpression directly.