Get companion object of class by given generic type Scala

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

    You could use reflection to get the companion class and its instance, but that relies on Scala internals that might change in some far(?) future. And there is no type safety as you get an AnyRef. But there is no need to add any implicits to your classes and objects.

    def companionOf[T : Manifest] : Option[AnyRef] = try{
      val classOfT = implicitly[Manifest[T]].erasure
      val companionClassName = classOfT.getName + "$"
      val companionClass = Class.forName(companionClassName)
      val moduleField = companionClass.getField("MODULE$")
      Some(moduleField.get(null))
    } catch {
      case e => None
    }
    
    case class A(i : Int)
    
    companionOf[A].collect{case a : A.type  => a(1)}
    // res1: Option[A] = Some(A(1))
    

提交回复
热议问题