Inheritance 关于反射和继承的Kotlin伴生对象限制
假设:Inheritance 关于反射和继承的Kotlin伴生对象限制,inheritance,kotlin,reflection,kotlin-companion,Inheritance,Kotlin,Reflection,Kotlin Companion,假设: 对于Parent 对于Parent 我有50多个子类的Parent clazz和一些其他字段由于性能原因必须按类(而不是实例)计算 期望伴随方法和非伴随方法使用计算成员(例如:clazz) 最后但并非最不重要的一点Parent和MyCompanion可能具有复杂的逻辑,但Parent的子类,如Child应尽可能采用最简单的形式 问题: 如何在以下两个表达式中检索子级的正确类名: Child().printClass() Child.printClassUsingCompanion()
- 对于
Parent
- 对于
Parent
- 我有50多个子类的
Parent
和一些其他字段由于性能原因必须按类(而不是实例)计算clazz
- 期望伴随方法和非伴随方法使用计算成员(例如:
)clazz
- 最后但并非最不重要的一点
和Parent
可能具有复杂的逻辑,但MyCompanion
的子类,如Parent
应尽可能采用最简单的形式Child
Child().printClass()
Child.printClassUsingCompanion()
代码:
open class MyCompanion {
var clazz = this::class.java.declaringClass.name
// and many more members that will compute using reflection with complex logic
fun printClassUsingCompanion() = println(clazz)
}
open class Parent {
companion object : MyCompanion()
fun printClass() = println(clazz)
}
class Child: Parent() {
companion object : MyCompanion()
}
fun main() {
Child().printClass() //output: Parent
Child.printClassUsingCompanion() //output: Child
}