Scala instantiate objects from String classname

馋奶兔 提交于 2019-12-21 17:24:00

问题


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.


回答1:


You can use reflections as follows:

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


来源:https://stackoverflow.com/questions/32384370/scala-instantiate-objects-from-string-classname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!