How to convert a PsiElement to a PsiClass
PsiElement referenceAt = psiFile.findElementAt(editor.getCaretModel().getOffset());
PsiClass parentOfType = PsiTreeUtil.getParentOfType(referenceAt, PsiClass.class);
WriteCommandAction.runWriteCommandAction(project, () -> {if (referenceAt instanceof PsiClass){
editor.getDocument().insertString(editor.getCaretModel().getOffset(), "isClass");
} else if (referenceAt instanceof PsiVariable){
editor.getDocument().insertString(editor.getCaretModel().getOffset(), "isVariable");
}
}
Right now I can extract the name of the Element that the caret is standing at. My goal is to find out whether or not the PsiElement is Class.
How can I accomplish this?
Please sign in to leave a comment.
Hello Osama,
> to find out whether or not the PsiElement is Class.
does
psiElement instanceof PsiClass
do it?
No that always returns false.
always null?
That returns the name of the class the Type is contained in.
looks like PsiTreeUtil.getParentOfType returns PsiElement subclass:
public static <T extends PsiElement> T getParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass)
Are you using PsiViewer plugin?
yeah. through that I resolved the the Types will show up as JavaTypeReference.
the way I have written it is a bit "circle-y". I wonder if this is really the correct way to get the Type.
PsiElement referenceAt = psiFile.findElementAt(editor.getCaretModel().getOffset());
try {
PsiJavaCodeReferenceElement context = (PsiJavaCodeReferenceElement) ((PsiIdentifier) referenceAt).getContext();
return true;
} catch (ClassCastException e) {
return false;
} catch (NullPointerException ne) {
return false;
}
Is this what you are looking for?
http://stackoverflow.com/a/33810502/500478
yes, Osama, could you give some background / context as to what you are trying to do?
I was trying to solve a problem which was not obvious to me.
My goal is to find out the fully qualified name of a Type, look it up in a mapping of mine and then add a provision to my android manifest.
That would be XML manipulation, maybe you detail that too.
I haven't had a chance to test out your answer there Bastien.
if you work with Java and XML, you need to find out about Java pre-built Element types (which you may already know).
You'd also need to find XML element factory to add new elements to the manifest.
I did not work with Java & XML language types so no ready answer.
to let user interact with the code, these tutorials describe one such option:
http://www.jetbrains.org/intellij/sdk/docs/tutorials/custom_language_support/annotator.html
http://www.jetbrains.org/intellij/sdk/docs/tutorials/custom_language_support/quick_fix.html
ElementFactory is described here
http://www.jetbrains.org/intellij/sdk/docs/tutorials/custom_language_support/reference_contributor.html
at
10.3. Define an element factory
did you git clone the community edition already? You'd need that and time: the more - the better.