8

I have a trait, Action, that many different classes, ${whatever}Action, extend. I'd like to make the class that is in charge of instantiating these Action objects dynamic in the sense that it will not know which of the extending objects it will be building until it is passed a String with the name. I want it to take the name of the class, then build the object based on that String.

I'm having trouble finding a concise/recent answer regarding this simple bit of reflection. I was hoping to get some suggestions as to either a place to look, or a slick way of doing this.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
turbo_laser
  • 261
  • 3
  • 16
  • Why are you looking to do this with reflection rather than a `match` (or similar)? – Ryan Sep 03 '15 at 21:26
  • 1
    I need it to be highly extensible. There could be hundreds of these actions and that case statement would get ginormous quickly. – turbo_laser Sep 04 '15 at 14:01

1 Answers1

8

You can use reflections as follows:

def actionBuilder(name: String): Action = {
  val action = Class.forName("package." + name + "Action").getDeclaredConstructor().newInstance()
  action.asInstanceOf[Action]
}
ecoe
  • 4,994
  • 7
  • 54
  • 72
Philosophus42
  • 472
  • 3
  • 11