Search code examples
reflectionscalasingleton

Getting object instance by string name in scala


I need the object (or "singleton object" or "companion object"... anything but the class) defined by a string name. In other words, if I have:

package myPackage
object myObject

...then is there anything like this:

GetSingletonObjectByName("myPackage.myObject") match {
  case instance: myPackage.myObject => "instance is what I wanted"
}

Solution

  • Scala is still missing a reflection API. You can get the an instance of the companion object by loading the companion object class:

    import scala.reflect._
    def companion[T](implicit man: Manifest[T]) : T = 
      man.erasure.getField("MODULE$").get(man.erasure).asInstanceOf[T]
    
    
    scala> companion[List$].make(3, "s")
    res0: List[Any] = List(s, s, s)
    

    To get the untyped companion object you can use the class directly:

    import scala.reflect.Manifest
    def companionObj[T](implicit man: Manifest[T]) = { 
      val c = Class.forName(man.erasure.getName + "$")
      c.getField("MODULE$").get(c)
    }
    
    
    scala> companionObj[List[Int]].asInstanceOf[List$].make(3, "s")
    res0: List[Any] = List(s, s, s)
    

    This depends on the way scala is mapped to java classes.