Objects and companions
We can even get a reference to objects or companion
objects through reflection. For example, take the following definition of a class and a companion
object:
class Aircraft(name: String, manufacturer: String, capacity: Int) { companion object { fun boeing(name: String, capacity: Int) = Aircraft(name, "Boeing", capacity) } }
Given this, we can retrieve a reference to the companion
object using the appropriately named companionObject
property defined on the KClass type:
val kclass = Aircraft::class val companionKClass = kclass.companionObject
From then on, we have another KClass instance, this one modeling the functions and members of the companion object.
In fact, using the companionObjectInstance
property, we can even get a handle to the instance of the companion
object. Then, we could invoke functions or access properties on it directly if we cast to the appropriate type:
val kclass = Aircraft::class val...