Get companion object of class by given generic type Scala

前端 未结 4 1316
星月不相逢
星月不相逢 2020-12-08 04:35

What I am trying to do is to make a function that would take a generic class and use a static method in it (sorry for Java language, I mean method of its companion object).<

4条回答
  •  遥遥无期
    2020-12-08 05:17

    I keep hitting this page when I forget how to do this and the answers are not hundred percent satisfactory for me. Here is how I do with reflection:

    val thisClassCompanion = m.reflect(this).symbol.companion.asModule
    val structural = m.reflectModule(thisClassCompanion)
                      .instance.asInstanceOf[{def doSth: Unit}]
    

    You might need to verify that the class actually has a companion object or companion.asModule will throw a reflection exception is not a module

    Updated: added another example for clarity:

        object CompanionUtil {
    
      import scala.reflect.runtime.{currentMirror => cm}
    
      def companionOf[T, CT](implicit tag: TypeTag[T]): CT = {
        Try[CT] {
          val companionModule = tag.tpe.typeSymbol.companion.asModule
          cm.reflectModule(companionModule).instance.asInstanceOf[CT]
        }
      }.getOrElse(throw new RuntimeException(s"Could not get companion object for type ${tag.tpe}"))
    
    }
    

提交回复
热议问题