Assume:
- I need a lot of companion (static-like) methods for subclasses of
Parent
- I need a lot of method (non-static) for subclasses of
Parent
- I have more than 50 subclasses of
Parent
clazz
and some other fields must compute per class (not instance) due to performance- Very Important:
Parent
andMyCompanion
can have complicated logic but subclasses ofParent
likeChild
should be in the simplest form as possible
Question:
how to retrieve correct class name of Child
in both below expressions:
Child().printClass()
Child.printClassUsingCompanion()
Code:
open class MyCompanion {
var clazz = this::class.java.declaringClass.name
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
}
Aucun commentaire:
Enregistrer un commentaire