Kotlin/JS 反射

Kotlin/JS provides a limited support for the Kotlin reflection API. The only supported parts of the API are:

Class references

The ::class syntax returns a reference to the class of an instance, or the class corresponding to the given type. In Kotlin/JS, the value of a ::class expression is a stripped-down KClass implementation that supports only:

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

KType and typeOf()

The typeof() function constructs an instance of KType for a given type. The KType API is fully supported in Kotlin/JS except for Java-specific parts.

Example

Here is an example of the reflection usage in Kotlin/JS.

  1. open class Shape
  2. class Rectangle : Shape()
  3. inline fun <reified T> accessReifiedTypeArg() =
  4. println(typeOf<T>().toString())
  5. fun main() {
  6. val s = Shape()
  7. val r = Rectangle()
  8. println(r::class.simpleName) // Prints "Rectangle"
  9. println(Shape::class.simpleName) // Prints "Shape"
  10. println(Shape::class.js.name) // Prints "Shape"
  11. println(Shape::class.isInstance(r)) // Prints "true"
  12. println(Rectangle::class.isInstance(s)) // Prints "false"
  13. val rShape = Shape::class.cast(r) // Casts a Rectangle "r" to Shape
  14. accessReifiedTypeArg<Rectangle>() // Accesses the type via typeOf(). Prints "Rectangle"
  15. }