How to invoke method on companion object via reflection?

后端 未结 3 1722
长发绾君心
长发绾君心 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:20

    The Scala 2.13.3 example coding below invokes a common method apply, in two different cases, by finding the companion object refering to the respective example class:

    package spielwiese.reflection_versuche
    
    object Structural_Typing_Companion_Object_Invoke_Testframe {
    
      // Example 1
      case class Person01(vorname: String, name: String)
    
      object Person01 {
        def apply(x: Integer): Person01 = new Person01(s"Prename_$x", s"Lastname_$x")
      }
    
      // Example 2
      case class Person02(vorname: String, name: String)
    
      object Person02 {
        def apply(x: Integer): Person02 = new Person02(s"Prename_$x", s"Lastname_$x")
      }
    
      // Invocation demo:
    
      import scala.reflect.runtime.{universe => ru}
    
      def callGenericCompanionObjectMethod[T](implicit typetag: ru.TypeTag[T]) = {
    
        val m = ru.runtimeMirror(getClass.getClassLoader)
    
        val o1 = m.reflectModule(ru.typeOf[T].typeSymbol.companion.asModule).instance
    
        val o2 = o1.asInstanceOf[{ def apply(x: Integer): T }] // "structural typing"
    
        o2.apply(123)
    
      }
    
      def main(args: Array[String]): Unit = {
    
        println(callGenericCompanionObjectMethod[Person01]) 
        // prints: "Person01(Prename_123,Lastname_123)"
    
        println(callGenericCompanionObjectMethod[Person02]) 
        // prints: "Person02(Prename_123,Lastname_123)"
    
      }
    
    }
    

提交回复
热议问题