Christopher Porto
09/23/2022, 11:38 PMjw
09/23/2022, 11:44 PMChristopher Porto
09/23/2022, 11:47 PMannotation class Foo(val clazz: KClass<...>
the KSP processor works fine until I try accessing the KClass since its not in class path which I get exception in runtimeChristopher Porto
09/23/2022, 11:48 PMjw
09/23/2022, 11:49 PMChristopher Porto
09/23/2022, 11:50 PMJake Woods
09/24/2022, 7:41 AMKClass
definitions to a KClassDeclaration
using as
if they have come from an annotation valueDavid Rawson
09/24/2022, 7:25 PMKClass
args as KSType
, from which you can get the declaration:
val ksType = ksAnnotated.getAnnotationsByType(Foo::class).single().arguments.single { it.name.asString() == "clazz" }.value as KSType
val declaration = ksType.declaration
val simpleName = declaration.simpleName.asString() // Bar etc.
Christopher Porto
09/24/2022, 7:33 PMJake Woods
09/27/2022, 4:54 AMinline fun <reified A : Annotation> KSAnnotation.getKClassArgument(
property: KProperty1<A, *>
): KSType {
val argument = this.arguments.find { it.name?.asString() == property.name } ?: run {
val validNames = this.arguments.mapNotNull { it.name?.asString() }.joinToString(", ")
error("Could not find annotation argument ${property.name}. (Valid names: $validNames)")
}
return (argument.value as? KSType) ?: error("${property.name} is not a valid KSType")
}
Assuming we have an annotation like this:
annotation class MyAnnotation(val klass: KClass<*>)
Then we can use the extension like so:
myAnnotationReference.getKClassArgument(MyAnnotation::klass)
Christopher Porto
09/27/2022, 5:12 AMgetAnnotationsByType
which returns the instance of the annotation and not the KSAnnotation
😛