[reflection] How to get companion object and new instance from ::class via reflection?


#1

 

class A{
  companion object{
  fun fn(){
          println(“A”)
  }
  }
}

class B{
  companion object{
  fun fn(){
          println(“B”)
  }
  }
}

fun invokeFnInCompanion(cl : KClass<*>){
  //???
}

fun invokeCtor<T>(cl : KClass<T>):T{
  //???
}

invokeFnInCompanion(A::class) // must print A
invokeFnInCompanion(B::class) // must print B
invokeCtor(A::class) // must return new instance A
invokeCtor(B::class) // must return new instance B


How to write body of invokeFnInCompanion?
How to write body of invokeCtor?


#2
Companion object is a named object whose name is Companion. So, this will get a class reference to the companion object: A.Companion::class. In the same fashion, to get a function reference to fn you can write A.Companion::fn. New instance construction is not yet supported in Kotlin reflection.