Can Kotlin convert Java reflection methods into higher-order functions? How to do it if possible?
Here is just an example, actual execution will result in an error.
class A {
fun haveFun(s:String){
print(s);
}
}
fun main(args: Array<String>) {
val forName = Class.forName("com.gwsoft.tests.A")
forName?.let {
val method = forName.getMethod("haveFun", String::class.java)
method?.let {
val fu=method as ((s:String)-> Unit)//这里并不行 会报java.lang.reflect.Method cannot be cast to kotlin.jvm.functions.Function1
fu("呵呵呵");
}
}
}
Reflection is not possible, but for a single abstract method interface (SAM Type), Kotlin has a SAM conversion mechanism when calling java, so you can use lambda~
For example, view.post{dosomething()}, which is equivalent to The post function that requires the Runnable interface is converted into a higher-order function.
More: http://www.jianshu.com/p/6386...