如何通过名称获取对Kotlin对象的引用? [英] How can I get a reference to a Kotlin object by name?
本文介绍了如何通过名称获取对Kotlin对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有顶层对象声明
package com.example
object MyObject {}
如何将字符串com.example.MyObject
转换为对MyObject
的引用?
how can I convert the string com.example.MyObject
into a reference to MyObject
?
推荐答案
如果您 kotlin-reflect
,然后可以使用 KClass
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
}
如果您没有kotlin-reflect
,则可以使用普通的旧Java语言方式
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
}
这篇关于如何通过名称获取对Kotlin对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文