How to get all PsiClass inside a PsiMethod?
已回答
As the title says, I want to get all psiClass used in a psiMethod.
I've tried 2 ways but they don't work:
1. use psiMethod.getOwnReferences()
for (PsiSymbolReference psiSymbolReference: psiMethod.getOwnReferences()) {
System.out.println(psiSymbolReference.getElement().getText());
}
The above code has no output, and I wonder why?
2. use complex way:
// get code block
PsiCodeBlock codeBlock = psiMethod.getBody();
if (codeBlock == null) {
return psiClassList;
}
// get statements
PsiStatement[] statements = codeBlock.getStatements();
for (int index = 0; index < statements.length; ++index) {
// whether it is a statement
if (statements[index] instanceof PsiExpressionStatement) {
PsiExpression psiExpression = ((PsiExpressionStatement) statements[index]).getExpression();
/**
* method call expression
*/
if (psiExpression instanceof PsiMethodCallExpression) {
...
}
/**
* new expression
*/
if (psiExpression instanceof PsiNewExpression) {
...
}
/**
* assignment expression
*/
if (psiExpression instanceof PsiAssignmentExpression) {
...
}
}
}
It is kind of complex and I might not be able to cover all situations(for expamle, recurrence for code block statement?).
So I wonder whether there's a way to get all PsiClass references inside a psimethod
请先登录再写评论。
Hi,
The
getOwnReferences()method returns the element’s own references, not all the references under its PSI node. So likely the references from getReferences(), and not from e.g. `PsiReferenceContributor`s.It’s unclear what it means to get all
PsiClass- all type occurrences (e.g.,String,List<String>, etc.) in a method body, allPsiClassof all elements in a method body (so, e.g., aPsiClassofmyFieldtype field defined out of the class body), orPsiClassfrom the method parameters?You have to implement the “complex” logic anyway, so get the element you want classes from and collect all the information. You should implement
PsiElementVisitor, which will collect this information and invoke it aspsiMethod.accept(myPsiClassCollector)and then get results.Thank you Karol Lewandowski
In fact, I want to get all PsiClass whose method is called or whose field is used(or inner class is used)
I wonder how to achive that