从scala对象动态访问方法

时间:2015-06-08 06:59:17

标签: scala dynamic reflection

在Scala中,动态调用对象并使用反射调用方法的最佳方法是什么?将调用与该对象相对应的方法,但该对象名称是动态已知的。

我能够从this SO question动态地实例化一个scala类,但是我需要为一个对象做同样的事情。

以下是一些示例代码:

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();
        }
    }
}

现在我是一个基类,它需要调用getC方法,但动态地知道相应的对象。那么如何实现同样的目标呢?

基类和我的疑问也在课堂评论中。

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")
   }
}

1 个答案:

答案 0 :(得分:3)

您仍然可以使用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 ...