4

I would like to be able to get an instance of a Scala Object from a String specified in config. Say for example I have a config property db.driver = "scala.slick.driver.H2Driver"

I would like to be able to get an instance of this object H2Driver. Obviously I could create a map of configs to actual objects, but that seems like a hassle. I could also do this by including a $ on the end of the config and loading up the module, i.e.

   val cl = Class.forName("scala.slick.driver.H2Driver$") //note the $
   val driverObj = cl.getField("MODULE$").get(null).asInstanceOf[JdbcProfile]

But I was hoping there was a neater way to do this in Scala 2.10 using the newer reflections API.

2
  • Sorry, I deleted my answer. I realised you are looking for a solution in 2.10 not 2.11 Commented May 5, 2014 at 12:49
  • Have you seen this stackoverflow.com/questions/11020746/… Commented May 5, 2014 at 15:09

1 Answer 1

3

Same in 2.10:

Welcome to Scala version 2.11.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import reflect.runtime._
import reflect.runtime._

scala> currentMirror staticModule "scala.Array"
res0: reflect.runtime.universe.ModuleSymbol = object Array

scala> currentMirror reflectModule res0
res1: reflect.runtime.universe.ModuleMirror = module mirror for scala.Array (bound to null)

scala> .instance
res2: Any = scala.Array$@67b467e9
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.