ZSp*_*tus 6 compiler-construction intellij-plugin kotlin intellij-platform-psi
我\xe2\x80\x99m 尝试开发一个codegen IDEA-Plugin。这个插件应该分析KtClass继承并获取所有继承类的全名(例如 com.example.config.TestConfig)
我尝试通过查看 PsiViewer 来查找任何有用的信息。我发现KtClass的所有继承信息都存储在 中KtSuperTypeEntry,并且我尽力获取继承类的全名。
上课Dest:
data class Dest(\n val stringValue: String = "123",\n override val stringConfig: String = "123",\n override val iConfigStr: String = "123",\n val b: B = B(),\n val c: List<List<Set<Map<String, out Any?>>>> = listOf(),\n val config: Config? = Config()\n) : Config()\nRun Code Online (Sandbox Code Playgroud)\n"Config"null看起来SuperTypeListEntry只包含继承类的简单名称信息。
\n我还尝试通过 KtFile 查找继承类全名,但不知道继承类何时作为通配符在此 KtFile 中导入:
\nfun KtSuperTypeListEntry.getType(ktFile: KtFile): String {\n val simpleName = superTypeListEntry.text\n\n // try to find by declared KtClass ...\n ktFile.children.filterIsInstance<KtClass>().filter { it.name == simpleName }\n\n // try to find by import ...\n ktFile.importDirectives.filter { it.importPath.toString().contains(simpleName) }\n\n \n // try to find by import wildcards ...\n ktFile.importDirectives.filter { it.importPath.toString().endWith("*") }.forEach {\n val split = it.importPath.split(".")\n split.set(split.size - 1, simpleName)\n val maybeFullName = split.joinToString(",") { it }\n // confused on how to detect "maybeFullName" is correct ...\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n如何从 Kotlin Psi API 检索所有继承类的全名?谢谢你!
\n经过数千次的调查和调试,我发现通过BindingContext找到一个类的继承类是可能的。BindingContext 可以分析 TypeReference 并找到 的引用KotlinType。代码可能是这样的:
ktClass.superTypeListEntries.map { superTypeEntry ->
val typeReference = superTypeEntry.typeReference
val bindingContext = typeReference.analyze()
bindingContext.get(BindingContext.TYPE, typeReference)
}.forEach { kotlinType ->
val classId = kotlinType.constructor.declarationDescriptor.classId
val packageName = classId.packageFqName
val simpleName = classId.relativeClassName
// It can also get the generics of this class by KotlinType.arguments
val generics = kotlinType.arguments
}
Run Code Online (Sandbox Code Playgroud)
另外,你可以通过 获取超类型的类全名KtLightClass,代码可能是这样的:
val ktLightClass = ktClass.toLightClass()
val superTypesFullName = ktLightClass?.supers?.forEach { superType ->
val packageName = superType.qualifiedName
val simpleName = superType.name
// you can get as KtClass by this, which can help you unify design of interface.
val ktClass = superType.kotlinOrigin
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
817 次 |
| 最近记录: |