I have a unary `annotation class` that accepts a `...
# compiler
m
I have a unary
annotation class
that accepts a
KClass<*>
. If I want to retrieve the type in my compiler plugin,
Copy code
@OptIn(SymbolInternals::class) annotatedClass.fir.annotations
    .first { annot ->
        annot.annotationTypeRef.coneType.classId == ANNOTATION_CLASS
    }
    .argumentMapping
    .mapping
    .values
    .single()
    .resolvedType
    .classId!!,
Is this the best I can do?
What’s the difference between the current
first
predicate
Copy code
annot.annotationTypeRef.coneType.classId == ANNOTATION_CLASS
and this alternative?
Copy code
@OptIn(UnresolvedExpressionTypeAccess::class)
annot.coneTypeOrNull?.classId == ANNOTATION_CLASS
y
I believe there's a
FirAnnotation.getXArgument
family of extensions that can help you here.
getKClassArgument
should be the one you're looking for (source)
m
@Youssef Shoaib [MOD] Wow,
.getKClassArgument(Name.identifier("kClass"))
should do the job then, right? (Is there a better way to obtain the
Name
, eg by querying the annotation class?) This is so much better, thank you!
❤️ 1
Also, I’ve browsed the API a little bit,
Copy code
@OptIn(SymbolInternals::class) annotatedClass.fir.annotations
    .getAnnotationByClassId(classId = ANNOTATION_CLASS, session = this.session)
And I think this is better than
Copy code
@OptIn(SymbolInternals::class) annotatedClass.fir.annotations
    .first { annot ->
        annot.annotationTypeRef.coneType.classId == ANNOTATION_CLASS
    }
This current version. But are there any subtle differences I should be aware of? Or can it be improved even further?
➕ 1
Copy code
annotatedClass
    .getAnnotationByClassId(classId = ANNOTATION_CLASS, session = this.session)!!
y
getAnnotationByClassId
seems to be better AFAIK. In general, I prefer using these utilities than accessing
argumentMapping
and such directly Re: querying the name: I think you can use
session.symbolProvider.getClassLikeSymbolByClassId
(source) to get the annotation class. What I've seen people do instead is add the relevant annotations library as a dependency in their plugins, and thus get access to the names from there (e.g. by doing
MyAnnotation::kClass.name
)
m
@Youssef Shoaib [MOD] Yes, I’ll use
getAnnotationByClassId
. Thanks for helping me discover it! Also, you mean by doing
Name.identifier(MyAnnotation::kClass.name)
, right? I also like this, thank you!