Get companion object of class by given generic type Scala

前端 未结 4 1287
星月不相逢
星月不相逢 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:26

    Based on the answer by Miquel, here's a method that gets the type reference of the companion object of the specified class object:

      /**
        * Returns the companion object type reference for the specified class
        *
        * @param clazz The class whose companion is required
        * @tparam CT Type of the companion object
        * @return The type of the relevant companion object
        */
      def companionOf[CT](clazz: Class[_]): CT = {
        import scala.reflect.runtime.{currentMirror => cm}
        Try[CT] {
          val companionModule = cm.classSymbol(clazz).companion.asModule
          cm.reflectModule(companionModule).instance.asInstanceOf[CT]
        }.getOrElse(throw new RuntimeException(s"Could not get companion object for $clazz"))
      }
    

提交回复
热议问题