Skip to content

Kotlin/JS のリフレクション ​

Kotlin/JS では、Kotlin のリフレクション API に対する限定的なサポートを提供しています。サポートされている API の部分は以下のみです:

クラス参照 ​

::class 構文は、インスタンスのクラス、または指定された型に対応するクラスへの参照を返します。 Kotlin/JS において、::class 式の値は機能を絞り込んだ KClass の実装であり、以下のみをサポートしています:

それに加えて、KClass.js を使用して、そのクラスに対応する JsClass インスタンスにアクセスできます。 JsClass インスタンス自体はコンストラクタ関数への参照です。 これは、コンストラクタへの参照を期待する JS 関数と相互運用するために使用できます。

KType and typeOf() ​

typeof() 関数は、指定された型に対する KType のインスタンスを構築します。 KType API は、Java 固有の部分を除き、Kotlin/JS で完全にサポートされています。

KClass and createInstance() ​

KClass インターフェースの createInstance() 関数は、指定されたクラスの新しいインスタンスを作成します。これは、Kotlin クラスへの実行時参照を取得する際に役立ちます。

例 ​

Kotlin/JS でのリフレクションの使用例を以下に示します。

kotlin
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" を出力
}