Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a reference to a Kotlin object by name?

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?

like image 347
Duncan McGregor Avatar asked Dec 18 '22 06:12

Duncan McGregor


2 Answers

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
}
like image 83
SerCe Avatar answered Jan 09 '23 05:01

SerCe


you can using kotlin reflection, for example:

val it = Class.forName("com.example.MyObject").kotlin.objectInstance as MyObject;
like image 29
holi-java Avatar answered Jan 09 '23 06:01

holi-java