0
votes

In Scala, what's the best way to dynamically call an object and invoke a method using reflection? The method corresponding to the object is to be called but the object name is known dynamically.

I was able to instantiate a scala class dynamically from this SO question however I need to do the same thing for an object.

Here is a sample code for some clarity:

class CC {
   def CC () = {
   }
}
object CC {
    def getC(name : String) : CC = {
        return new CC();
        }
    }
}
class CD {
   def CD () = {
   }
}
object CD {
   def getC(name : String) : CC = {
        return new CD();
        }
    }
}

Now I've a base class, which needs to call the getC method but the corresponding object is know dynamically. So how does one achieve the same?

Also the base class and my doubt is in the comments of the class.

class Base {
   def Base() = {
   }
   def createClass(name : String) = {
     // need to call the method corresponding to the object depending
     // on the string. 
     //e.g.: if name = "C" call CC.getC("abcd")
     //      if name = "D" call CD.getC("abcd")
   }
}
1

1 Answers

3
votes

You could still use scala runtime reflection:

import scala.reflect.runtime.{universe => ru}

val m = ru.runtimeMirror(getClass.getClassLoader)
val ccr = m.staticModule("my.package.name.ObjName") // e.g. "CC" or "CD"
type GetC = {
 def getC(name:String): CC
} 
val cco = m.reflectModule(ccr).instance.asInstanceOf[GetC]

now you could use it as cco.getC ...