Reputation: 15173
Say I have a function haveFun
which takes in a Method
(from java.lang.reflect
package) as a param and returns a lambda as below
typealias AnyFun = (o: Any?) -> Any?
fun haveFun(method: Method): AnyFun {
return { o -> method.invoke(o) }
}
data class Game(val name: String)
Now if I pass a method to the function and assign the lambda to a field as
val game = haveFun(Game::name.javaGetter!!)
Can I find out and access the Method
that was passed to the function using the above game
field which is a lambda?
I can see the Method
while debugging on Intellij, but not sure on how to access it.
Upvotes: 1
Views: 556
Reputation: 1906
You can access and use it through reflection as a declaredField having $method
name, as follows:
val methodField = game.javaClass.getDeclaredField("\$method")
val method = methodField.get(game) as Method
println(method.invoke(Game("Pietro"))) // outputs the String "Pietro"
Upvotes: 2