背景
有部分需求需要反射获取相关信息,例如,由于子类太多100+,需要在父类写toString方法涵盖子类的相关信息
实现过程
- 逻辑通过反射获取子类构造方法的参数
- 通过当前实例调用参数的获取方法,获取参数值
- 在父类的toString中输出和组建toString
代码
- 获取构造方法的参数
val pc = this::class.primaryConstructor
- 获取参数值
val props = this::class.memberProperties
- 组建数据
var childs: List<String> = emptyList()
if(pc != null){
childs = pc.parameters.map { pa -> props.find { it.name == pa.name }?.getter?.call(this).toString() }
}
return "A(${childs.joinToString()})"
- 全部代码
open class A {
override fun toString(): String {
val pc = this::class.primaryConstructor
val props = this::class.memberProperties
var childs: List<String> = emptyList()
if(pc != null){
childs = pc.parameters.map { pa -> props.find { it.name == pa.name }?.getter?.call(this).toString() }
}
return "A(${childs.joinToString()})"
}
}
class B(val a: String, val b: String) : A()
fun main() {
println(B("aaa", "bbb").toString())
}