从 scala 对象动态访问方法
Dynamically access methods from scala object
在 Scala 中,使用反射动态调用对象和调用方法的最佳方式是什么?要调用对象对应的方法,但是对象名是动态知道的
我能够从 this SO question 动态实例化一个 scala class 但是我需要为一个对象做同样的事情。
为了清楚起见,这里有一个示例代码:
class CC {
def CC () = {
}
}
object CC {
def getC(name : String) : CC = {
return new CC();
}
}
}
class CD {
def CD () = {
}
}
object CD {
def getC(name : String) : CC = {
return new CD();
}
}
}
现在我有一个基础class,它需要调用getC
方法,但相应的对象是动态知道的。那么如何实现同样的目标呢?
也是基础 class,我的疑问在 class 的评论中。
class Base {
def Base() = {
}
def createClass(name : String) = {
// need to call the method corresponding to the object depending
// on the string.
//e.g.: if name = "C" call CC.getC("abcd")
// if name = "D" call CD.getC("abcd")
}
}
您仍然可以使用 Scala 运行时反射:
import scala.reflect.runtime.{universe => ru}
val m = ru.runtimeMirror(getClass.getClassLoader)
val ccr = m.staticModule("my.package.name.ObjName") // e.g. "CC" or "CD"
type GetC = {
def getC(name:String): CC
}
val cco = m.reflectModule(ccr).instance.asInstanceOf[GetC]
现在您可以将其用作 cco.getC ...
在 Scala 中,使用反射动态调用对象和调用方法的最佳方式是什么?要调用对象对应的方法,但是对象名是动态知道的
我能够从 this SO question 动态实例化一个 scala class 但是我需要为一个对象做同样的事情。
为了清楚起见,这里有一个示例代码:
class CC {
def CC () = {
}
}
object CC {
def getC(name : String) : CC = {
return new CC();
}
}
}
class CD {
def CD () = {
}
}
object CD {
def getC(name : String) : CC = {
return new CD();
}
}
}
现在我有一个基础class,它需要调用getC
方法,但相应的对象是动态知道的。那么如何实现同样的目标呢?
也是基础 class,我的疑问在 class 的评论中。
class Base {
def Base() = {
}
def createClass(name : String) = {
// need to call the method corresponding to the object depending
// on the string.
//e.g.: if name = "C" call CC.getC("abcd")
// if name = "D" call CD.getC("abcd")
}
}
您仍然可以使用 Scala 运行时反射:
import scala.reflect.runtime.{universe => ru}
val m = ru.runtimeMirror(getClass.getClassLoader)
val ccr = m.staticModule("my.package.name.ObjName") // e.g. "CC" or "CD"
type GetC = {
def getC(name:String): CC
}
val cco = m.reflectModule(ccr).instance.asInstanceOf[GetC]
现在您可以将其用作 cco.getC ...