Kotlinreflection – 检查属性是否有types
我想遍历我的一个类中的所有字段,过滤注释的字段,然后检查字段是否有一个特定的types。
所有我发现是field.returnType.isSubtype(other: KType)
但我不知道如何得到我的其他类的KType
。
这是我的代码到目前为止:
target.declaredMemberProperties.forEach { if (it.findAnnotation() != null) { if ( /* it.returnType is Component <- Here I need some working check */ ) { // do stuff } else { // do ther stuff } } }
这里至少有两个解决方案:
-
使用
.jvmErasure
获取KClass<*>
,然后检查KClass
es的子types关系:it.returnType.jvmErasure.isSubclassOf(Component::class)
-
从Kotlin 1.1开始,您可以使用
.createType()
从KClass
标记.createType()
检查其可选参数:您可以使用它们提供可空性信息,types参数和注释),然后按照您的建议检查子types:it.returnType.isSubtypeOf(Component::class.createType())
在每次迭代中创建types可能会导致性能问题,请确保在经常需要时缓存它。