LoginSignup
0
0

More than 3 years have passed since last update.

【Kotlin】KFunctionから定義元objectのinstanceを取得する

Last updated at Posted at 2020-10-24

やりたいこと

KFunctionが渡された時、その定義元がobjectであれば、そのinstanceを取得します。
ただし、今回紹介する方法でトップレベル関数を処理するとjava.lang.UnsupportedOperationExceptionになるため注意が必要です。

やり方

以下のように、KFunctionからjavaMethodを経由することで取得できます。
もう少し素直な取得方法が無いものか確認しましたが、Kotlin 1.4.10時点ではKFunctiondeclaringClassのようなプロパティは無く、無理そうでした。

object Foo {
    fun function(i: Int) = i.toString() 
}

val function: KFunction<String> = (Foo)::function
val instance: Foo = function.javaMethod!!.declaringClass.kotlin.objectInstance as Foo
0
0
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
0
0