KClass 中 getClass() 的 Kotlin 等價物


在本文中,我們將舉一個例子,演示如何在 Kotlin 中獲取類引用。Kotlin 不支援直接獲取類引用,但您可以透過擴充套件本身來獲取相同的引用。在以下示例中,我們將看到如何透過 Kotlin 庫函式實現此目的。

示例 - 使用 KClass 的類引用

在此示例中,我們將獲得該類的引用。

import kotlin.reflect.KClass

fun main(args : Array<String>) {
   // to get the reference of the class
   fun<T: Any> T.getClass(): KClass<T> {
      return javaClass.kotlin
   }

   val myVariable = "String"
   val myAnotherVariable = 1

   // As the variable is of String type,
   // it will give us java.lang.String
   println("Kotlin type: ${myVariable.getClass()}")

   // this is of type Int
   println("Kotlin type: ${myAnotherVariable.getClass().simpleName}")
}

輸出

執行後,將產生以下輸出 -

Kotlin type: class kotlin.String
Kotlin type: Int

更新於: 2022-03-01

244 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.