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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP