4

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?

Duncan McGregor
  • 17,665
  • 12
  • 64
  • 118

3 Answers3

8

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
}
SerCe
  • 5,826
  • 2
  • 32
  • 53
  • considering we use a function to return an object instance from its name, what is the return type please? – fralbo Apr 13 '18 at 13:17
  • @fralbo `Any` would be the only reasonable return type in general (or `Any?` if you want to return `null` when there's no such `object`). – Alexey Romanov Apr 09 '21 at 17:45
2

you can using kotlin reflection, for example:

val it = Class.forName("com.example.MyObject").kotlin.objectInstance as MyObject;
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • 2
    If you can do `as MyObject`, you can write `MyObject` instead of all this in the first place :) – Alexey Romanov Jul 13 '18 at 19:18
  • @AlexeyRomanov But what if the string represents subclass and `as MyObject` casts it to a base class. Anyway, you can throw out `as MyObject` and consider this example as a good one-liner. – Mikolasan Apr 09 '21 at 16:14
  • "But what if the string represents subclass and `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. – Alexey Romanov Apr 09 '21 at 17:43
0

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