Kotlin反射 - 检查属性是否具有类型

4

我希望能够遍历我的一个类中的所有字段,筛选出已注释的字段,然后检查该字段是否具有一个特定的类型。
我找到的全部内容是field.returnType.isSubtype(other: KType),但我不知道如何获得另一个类的KType

以下是我的代码:

target.declaredMemberProperties.forEach {
    if (it.findAnnotation<FromOwner>() != null) {
        if ( /*  it.returnType is Component <- Here I need some working check   */ ) {

            // do stuff
         } else {

            // do ther stuff
         }
    }
}
1个回答

13

这里至少有两种解决方案:

  • 使用.jvmErasure获取it.returnTypeKClass<*>,然后检查KClass之间的子类型关系:

    it.returnType.jvmErasure.isSubclassOf(Component::class)
    
    自 Kotlin 1.1 开始,您可以使用 .createType()KClass 标记构造 KType(检查其可选参数:您可以使用它们提供 nullability 信息、类型参数和注释),然后按照您的建议检查子类型。
  • it.returnType.isSubtypeOf(Component::class.createType())
    

    如果您需要经常使用它,请确保缓存类型,因为在每次迭代中创建类型可能会引入性能问题。


这是否意味着在伴生对象中使用 val componentType by lazy { Component::class.createType() } 是一个好主意? - danielspaniol
@Exhauzt,我猜测对你特定的使用情况进行基准测试应该能够得出最好的答案。 - hotkey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接