Scala instance of objects from String classname

I have an Action trait that many different classes, $ {any} Action, expand. I would like to create a class that is responsible for instantiating these Action objects in the sense that it will not know which of the expanding objects it will build until a String with a name is passed. I want him to take the class name and then build an object based on this line.

I am having trouble finding a short / recent answer regarding this simple reflection. I was hoping to get some suggestions regarding a place to see, or a smooth way to do it.

+4
source share
1 answer

:

def actionBuilder(name: String): Action = {
  val action = Class.forName("package." + name + "Action").newInstance()
  action.asInstanceOf[Action]
}
+4

Source: https://habr.com/ru/post/1605824/


All Articles