Scala从String类名实例化对象 [英] Scala instantiate objects from String classname

查看:229
本文介绍了Scala从String类名实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特质Action,它可以扩展许多不同的类$ {whatever} Action.我想使负责实例化这些Action对象的类动态化,因为在将其传递给具有名称的String之前,它将不知道它将构建哪个扩展对象.我希望它使用类的名称,然后基于该字符串构建对象.

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.

推荐答案

您可以按如下方式使用反射:

You can use reflections as follows:

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

这篇关于Scala从String类名实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆