如何从父对象获取成员属性的名称

问题描述 投票:0回答:1

我想通过反射实现getMemberName函数

class Inner {
    val prop = ""
}
class Source {
    val member = ""
    val innerMember = Inner()
}
fun getMemberName(source: Any, member: Any) : String {
    return "..."
}
fun main() {
  val demo = Source()
  val memberName = getMemberName(demo, demo.member)
  //result: 'member'

  val innerMemberName = getMemberName(demo, demo.innerMember.prop)
  //result: 'innerMember.prop'
}

也许反射库中的某些存在任何通用的解决方案?

kotlin reflection
1个回答
0
投票

这可能是您想要的,但我认为您无法一次性找到从 Source 到第二个字段的“路径”,因为该字段是从对象层次结构中的位置取消引用的

class Inner {
    val prop = "x"
}
class Source {
    val member = "y"
    val innerMember = Inner()
}
fun getMemberName(source: Any, member: KProperty0<Any>) : String {
    return "${member.name} declared in ${member.javaField?.declaringClass?.name} has value ${member.get()}"
}

fun main() {
    val demo = Source()
    val memberName = getMemberName(demo, demo::member)
    println(memberName) // prints: member declared in Source has value y

    val innerMemberName = getMemberName(demo, demo.innerMember::prop)
    println(innerMemberName) // prints: prop declared in Inner has value x
}

如果您想构建一条从源向下 N 层深入到字段的路径,那么这会更困难,因为您已经设计了某种方式来传递属性引用。 “Bean Accessor”方法可能更适合您,例如 Apache Commons PropertyUtils

© www.soinside.com 2019 - 2024. All rights reserved.