【问题标题】:Kotlin - get all properties from primary constructorKotlin - 从主构造函数获取所有属性
【发布时间】:2019-02-16 19:47:14
【问题描述】:

我创建了这个扩展方法,它从 KClass<T> 获取所有属性

扩展方法

@Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> KClass<T>.getProperties(): Iterable<KProperty1<T, *>> {
    return members.filter { it is KProperty1<*, *> }.map { it as KProperty1<T, *> }
}

示例用法

data class Foo(val bar: Int) {
    val baz: String = String.EMPTY
    var boo: String? = null
}

val properties = Foo::class.getProperties()

结果

val com.demo.Foo.bar: kotlin.Int

val com.demo.Foo.baz: kotlin.String

var com.demo.Foo.boo: kotlin.String?

如何修改此扩展方法以仅返回在主构造函数中声明的属性?

预期结果

val com.demo.Foo.bar: kotlin.Int

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    您可以通过获取primaryConstructor然后获取valueParameters来获取构造函数参数, 并且因为 kotlin 类不需要主构造函数,我们可以做这样的事情

    inline fun <reified T : Any> KClass<T>.getProperties(): Iterable<KParameter> {
       return primaryConstructor?.valueParameters ?: emptyList()
    }
    

    如果我们要询问 Foo 类的属性

    val properties = Foo::class.getProperties()
    properties.forEach { println(it.toString()) }
    

    我们会得到

    parameter #0 bar of fun <init>(kotlin.Int): your.package.Foo
    

    结果不是一个 KProperty,而是一个可能更符合您的用例的 KParameter

    【讨论】:

      【解决方案2】:
      inline fun <reified T : Any> KClass<T>.getProperties(): List<KProperty<*>> {
          val primaryConstructor = primaryConstructor ?: return emptyList()
          // Get the primary constructor of the class ^
      
          return declaredMemberProperties.filter {
          // Get the declared properties of the class; i.e. bar, baz, boo
              primaryConstructor.parameters.any { p -> it.name == p.name } 
              // Filter it so there are only class-properties whch are also found in the primary constructor.
          }
      }
      

      总而言之,这个函数基本上获取一个类中找到的所有属性并过滤它们,因此只有在主构造函数中找到的也是的保留。

      【讨论】:

        猜你喜欢
        • 2019-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-31
        • 2021-02-18
        • 2015-09-11
        • 2019-08-03
        相关资源
        最近更新 更多