【问题标题】:How to know if object is a singleton in Kotlin?如何知道对象是否是 Kotlin 中的单例?
【发布时间】:2018-01-31 22:12:55
【问题描述】:

我想在超类中定义toString(),以便它检测到类实例是单例(object)并打印其名称。

在 Kotlin 中可以吗?

【问题讨论】:

  • 答案有帮助吗?

标签: object reflection kotlin singleton tostring


【解决方案1】:

KClass 的以下 objectInstance 属性可能会有所帮助:

/**
 * The instance of the object declaration, or `null` if this class is not an object declaration.
 */
public val objectInstance: T?

这是一个例子:

object Singleton

println(Singleton::class.objectInstance) // xx.Singleton@77a57272
println(""::class.objectInstance) //null

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多