how to access companion object from object instance in kotlin?
Using reflection, you can go via companionObject
:
sample::class.companionObject?.memberProperties?.find { it.name == "test" }
The problems is that while object properties are accessible from outside the class provided they are not public, but properties of the companion object are not. This means adding getters (and if relevant setters) for any companion object properties to be accessed externally to the class.
class MyClass{
companion object{
val test = 25
}
var staticTest get() = test // getter for test
}
then all that is needed for access is::
sample.staticTest
Or you can provide access to the companion object...
class MyClass{
companion object{
val test = 25
}
var companion = Companion
}
Then allowing full access to anything in the companion