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