Kotlin反思 - 检查财产是否有类型

dan*_*iol 2 reflection kotlin

我想迭代我的一个类中的所有字段,过滤注释的字段,然后检查字段是否有一个特定的类型.
我发现的只是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
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

hot*_*key 9

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

  • 获取KClass<*>it.returnType使用.jvmErasure,然后检查的亚型关系KClassES:

    it.returnType.jvmErasure.isSubclassOf(Component::class)
    
    Run Code Online (Sandbox Code Playgroud)
  • 由于科特林1.1,您可以构建KTypeKClass使用令牌.createType()(检查它的可选参数:您可以使用他们提供的为空信息,类型参数和注释),然后检查亚型如你所说:

    it.returnType.isSubtypeOf(Component::class.createType())
    
    Run Code Online (Sandbox Code Playgroud)

    在每次迭代时创建类型可能会引入性能问题,请确保在需要时对其进行缓存.