在 Scala 中通过字符串名称获取对象实例 [英] Getting object instance by string name in scala
本文介绍了在 Scala 中通过字符串名称获取对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要由字符串名称定义的对象(或单个对象"或伴随对象"...除了类之外的任何东西).换句话说,如果我有:
I need the object (or "singleton object" or "companion object"... anything but the class) defined by a string name. In other words, if I have:
package myPackage
object myObject
...那么有没有这样的:
...then is there anything like this:
GetSingletonObjectByName("myPackage.myObject") match {
case instance: myPackage.myObject => "instance is what I wanted"
}
推荐答案
Scala 仍然缺少反射 API.可以通过加载伴生对象类来获取伴生对象的实例:
Scala is still missing a reflection API. You can get the an instance of the companion object by loading the companion object class:
import scala.reflect._
def companion[T](implicit man: Manifest[T]) : T =
man.erasure.getField("MODULE$").get(man.erasure).asInstanceOf[T]
scala> companion[List$].make(3, "s")
res0: List[Any] = List(s, s, s)
要获得无类型的伴生对象,您可以直接使用该类:
To get the untyped companion object you can use the class directly:
import scala.reflect.Manifest
def companionObj[T](implicit man: Manifest[T]) = {
val c = Class.forName(man.erasure.getName + "$")
c.getField("MODULE$").get(c)
}
scala> companionObj[List[Int]].asInstanceOf[List$].make(3, "s")
res0: List[Any] = List(s, s, s)
这取决于scala映射到java类的方式.
This depends on the way scala is mapped to java classes.
这篇关于在 Scala 中通过字符串名称获取对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文