How to invoke method on companion object via reflection?

后端 未结 3 1730
长发绾君心
长发绾君心 2020-12-16 23:39

I have a class name and a method whose type parameters I know, and I\'d like to invoke this method via reflection.

In java I\'d do something like:

Cl         


        
3条回答
  •  天命终不由人
    2020-12-17 00:28

    Refer scala doc reflection overview

    // get runtime universe
    val ru = scala.reflect.runtime.universe
    
    // get runtime mirror
    val rm = ru.runtimeMirror(getClass.getClassLoader)
    
    // define class and companion object
    class Boo{def hey(x: Int) = x}; object Boo{def hi(x: Int) = x*x}
    
    // get instance mirror for companion object Boo
    val instanceMirror = rm.reflect(Boo)
    
    // get method symbol for the "hi" method in companion object
    val methodSymbolHi = ru.typeOf[Boo.type].decl(ru.TermName("hi")).asMethod
    
    // get method mirror for "hi" method
    val methodHi = instanceMirror.reflectMethod(methodSymbolHi)
    
    // invoke the method "hi"
    methodHi(4)  // 16
    

提交回复
热议问题