Finding a singleton via reflection


#1

I want to find all object derived from a certain class (Config), what is easy to do with the Reflections library:

interface Config {
  val name: String
}

object MyConfig : Config {
  override val name = "demo"
}

val reflections = Reflections("org.demo")
val configClass = reflections.getSubTypesOf(Config::class.java).first()

I get the class as expected. But how do I get the singleton object MyConfig for this class? I don’t want to create a new instance, but get the existing one.


#2

You do this using the objectInstance property: http://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-class/object-instance.html


#3

Thanks. And how do I get a KClass instance in this case? “reflections” returns Classes.


#4

You can use .kotlin to get a KClass for any Java class.


#5

Thank you!