为什么要在Kotlin的班级会员财产反思?

发布于 2025-02-03 02:45:50 字数 425 浏览 2 评论 0原文

在“ Kotlin In Action”中,它说:“如果成员Property指的是人类班级的年龄属性,则会成员Property.get(Person)是一种动态获取人的价值的方式。反射API):

class Peron(val name: String, val age: Int)
>> val person = Person("Alice", 29)
>> val memberProperty = Person::age
>> println(memberProperty.get(person))
29

我不明白为什么此示例是指“动态”获得属性的价值。当我运行此代码时,它只是有效的:

println(person.age)

是否还有其他成员属性反射的情况或示例?

In 'Kotlin in Action', it says "if a memberProperty refers to the age property of the Person class, memberProperty.get(person) is a way to dynamically get the value of person.age" with code(10.2.1 The Kotlin Reflection API):

class Peron(val name: String, val age: Int)
>> val person = Person("Alice", 29)
>> val memberProperty = Person::age
>> println(memberProperty.get(person))
29

I can't understand why this example refers to "dynamically" getting the value of property. It just works when I run this code:

println(person.age)

Is there any other case or example of member property reflection?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如果没有你 2025-02-10 02:45:50

例如,假设您要编写一个函数,该函数及其值及其值以及您可以做到这一点:

inline fun <reified T: Any> T.printProperties() {
    T::class.memberProperties.forEach { property ->
        println("${property.name} = ${property.get(this)}") // You can't use `this.property` here
    }
}

用法:

data class Person(val firstName: String, val lastName: String)
data class Student(val graduate: Boolean, val rollNumber: Int)

fun main() {
    val person = Person("Johnny", "Depp")
    val student = Student(false, 12345)
    person.printProperties()
    student.printProperties()
}

输出:

firstName = Johnny
lastName = Depp
graduate = false
rollNumber = 12345

For example, say you want to write a function which prints all the properties of an object along with their values, this is how you can do that:

inline fun <reified T: Any> T.printProperties() {
    T::class.memberProperties.forEach { property ->
        println("${property.name} = ${property.get(this)}") // You can't use `this.property` here
    }
}

Usage:

data class Person(val firstName: String, val lastName: String)
data class Student(val graduate: Boolean, val rollNumber: Int)

fun main() {
    val person = Person("Johnny", "Depp")
    val student = Student(false, 12345)
    person.printProperties()
    student.printProperties()
}

Output:

firstName = Johnny
lastName = Depp
graduate = false
rollNumber = 12345
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文