1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Kotlin】KTypeからKClassを取得する

Posted at

やること

Kotlinのリフレクションで取れるKTypeからKClassを取得します。

やり方

例として、ラムダから引数のKClassを取る例を示します。

val lambda: (String?) -> Any? = { /* ラムダの内容は省略 */ }
val reflect: KFunction<Any?> = lambda.reflect()!!

val kType: KType = reflect.parameters.first().type
val classifier = type.classifier!!

// 実際にはKClass<String>が取れる
val kClass: KClass<*> = classifier as KClass<*>

実際にはKClass<String>が取れてしまって(= nullabilityの情報が消えて)いますが、一応KClassが取得できました。

参考にさせて頂いた記事

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?