12.4.4 KSP 示例
原文链接: https://kotlinlang.org/docs/ksp-examples.html
12.4.4 KSP 示例
获取所有成员函数
1
2
| fun KSClassDeclaration.getDeclaredFunctions(): Sequence<KSFunctionDeclaration> =
declarations.filterIsInstance<KSFunctionDeclaration>()
|
检查类或函数是否为局部声明
1
2
| fun KSDeclaration.isLocal(): Boolean =
parentDeclaration != null && parentDeclaration !is KSClassDeclaration
|
查找类型别名所指向的实际类或接口声明
1
2
3
4
5
6
7
8
| fun KSTypeAlias.findActualType(): KSClassDeclaration {
val resolvedType = this.type.resolve().declaration
return if (resolvedType is KSTypeAlias) {
resolvedType.findActualType()
} else {
resolvedType as KSClassDeclaration
}
}
|
收集文件注解中被抑制的名称
1
2
3
4
5
6
7
8
9
10
| // @file:kotlin.Suppress("Example1", "Example2")
fun KSFile.suppressedNames(): Sequence<String> = annotations
.filter {
it.shortName.asString() == "Suppress" &&
it.annotationType.resolve().declaration.qualifiedName?.asString() == "kotlin.Suppress"
}.flatMap {
it.arguments.flatMap {
(it.value as Array<String>).toList()
}
}
|