If I have a top level object declaration
package com.example
object MyObject {}
how can I convert the string com.example.MyObject into a reference to MyObject?
If you have kotlin-reflect on the classpath then you can use the objectInstance property of KClass
fun main(args: Array<String>) {
val fqn = "com.example.MyObject"
val clz: Class<*> = Class.forName(fqn)
val instance = clz.kotlin.objectInstance
println(instance) // com.example.MyObject@71623278
}
if you don't have kotlin-reflect then you can do it in a plain old java-way
fun main(args: Array<String>) {
val fqn = "com.example.MyObject"
val clz: Class<*> = Class.forName(fqn)
val field: Field = clz.getDeclaredField("INSTANCE")
val instance = field.get(null)
println(instance) // com.example.MyObject@76ed5528
}
Any would be the only reasonable return type in general (or Any? if you want to return null when there's no such object).you can using kotlin reflection, for example:
val it = Class.forName("com.example.MyObject").kotlin.objectInstance as MyObject;
as MyObject, you can write MyObject instead of all this in the first place :)as MyObject casts it to a base class. Anyway, you can throw out as MyObject and consider this example as a good one-liner.as MyObject casts it to a base class" Doesn't apply to this question, where MyObject is an object which can't be extended. "you can throw out as MyObject" Yes, I agree.