Find All Fields with Specified Annotation and Read their attributes

Hi, all,


We want to find all fields in user codes, which are annotated with a specified annotation on them(e.g. com.xxx.annotation.Anno).

I try to do that with codes like:

PsiClass clazz = JavaFacade.getInstance(project).findClass(fqcn, scope);

Query<PsiReference> query = ReferencesSearch.search(clazz, ProjectScopeBuilder.getInstance(project).buildProjectScope());

for(PsiReference ref : query) {

if( ((PsiElement)ref).getParent() instanceof PsiAnnotation ) {

PsiElement element = ((PsiElement)ref).getParent();

if(element.getParent() instanceof PsiField) {

process(element);

}

}

}

It looks good. But, because all annotated field MUST be found, Does the mentioned code work on all kinds of codes?

 

Meanwhile, we have to read the value of some attribute in the annotation.

@Anno(ns="a")

this is easy to be read. But

@Anno(ns=NS_PREFIX+"a")

is quite difficult. User will use some constants in the attribute, and the constants might be calculated with other constants.

How can we get the real value of the attribute like the "resolved value" in the tip(when we press "ctrl" and move mouse on the Constants reference)?

 

Thanks,

 

Meilun Sheng

0
1 comment
Avatar
Permanently deleted user

well, I found that PsiConstantEvaluationHelper may solve the second problem.

 

PsiAnnotationMemberValue value = annotation.findAttributeValue(attributeName);

if(value instanceof PsiArrayInitializerMemberValue) {

    PsiArrayInitializerMemberValue arrayValue = (PsiArrayInitializerMemberValue) value;

    for(PsiAnnotationMemberValue itemValue : arrayValue.getInitializers()) {

        process(psiFacade.getConstantEvaluationHelper().computeConstantExpression(itemValue));

    }

} else {

    process(psiFacade.getConstantEvaluationHelper().computeConstantExpression(value);

}

 

Does this code cover all possible situations?

0

Please sign in to leave a comment.