7.2.7 Kotlin/JS 反射

原文链接: https://kotlinlang.org/docs/js-reflection.html

7.2.7 Kotlin/JS 反射

Kotlin/JS 对 Kotlin 反射 API提供有限支持。API 中受支持的部分只有:

类引用

::class 语法会返回对某个实例所属类的引用,或与给定类型相对应的类。在 Kotlin/JS 中,::class 表达式的值是一个精简版的 KClass 实现,它只支持:

除此之外,你还可以使用 KClass.js 访问与该类对应的 JsClass 实例。JsClass 实例本身就是对构造函数函数的引用。这可用于与那些期望接收构造函数引用的 JS 函数互操作。

KType 与 typeOf()

typeof() 函数会为给定类型构造一个 KType 实例。除 Java 特有的部分之外,KType API 在 Kotlin/JS 中得到完整支持。

KClass 与 createInstance()

KClass 接口中的 createInstance() 函数会创建指定类的新实例,这对于获取 Kotlin 类的运行时引用很有用。

示例

下面是一个在 Kotlin/JS 中使用反射的例子。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
open class Shape
class Rectangle : Shape()

inline fun <reified T> accessReifiedTypeArg() =
    println(typeOf<T>().toString())

fun main() {
    val s = Shape()
    val r = Rectangle()

    println(r::class.simpleName) // 打印 "Rectangle"
    println(Shape::class.simpleName) // 打印 "Shape"
    println(Shape::class.js.name) // 打印 "Shape"

    println(Shape::class.isInstance(r)) // 打印 "true"
    println(Rectangle::class.isInstance(s)) // 打印 "false"
    val rShape = Shape::class.cast(r) // 把 Rectangle 实例 "r" 转换为 Shape

    accessReifiedTypeArg<Rectangle>() // 通过 typeOf() 访问类型。打印 "Rectangle"
}