Home  >  Q&A  >  body text

Can Kotlin convert Java reflection methods into higher-order functions? How to do it if possible?

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

reply all(1)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-23 09:15:40

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

    reply
    0
  • Cancelreply