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 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;
Same a java code, you need use Class.forName("com.example.MyObject")
. Now you have a Java class, but using kotlin
extension, it convert to Kotlin class. Class.forName("com.example.MyObject").kotlin