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?

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

considering we use a function to return an object instance from its name, what is the return type please?
@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).
2

you can using kotlin reflection, for example:

val it = Class.forName("com.example.MyObject").kotlin.objectInstance as MyObject;

3 Comments

If you can do as MyObject, you can write MyObject instead of all this in the first place :)
@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.
"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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.