Can Kotlin convert Java reflection methods into higher-order functions? How to do it if possible?
扔个三星炸死你
扔个三星炸死你 2017-06-23 09:13:40
0
1
805

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("呵呵呵");
        }
    }
}
扔个三星炸死你
扔个三星炸死你

reply all(1)
仅有的幸福

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...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template