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
}
you can using kotlin reflection, for example:
val it = Class.forName("com.example.MyObject").kotlin.objectInstance as MyObject;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With