How do I call a Scala Object method using reflection?

前端 未结 3 823
清歌不尽
清歌不尽 2020-11-30 02:55

say, I have the following:

trait SomeTrait {
  def someMethod: String;
}

object SomeObject extends SomeTrait {
  def someMethod = \"something\";
}
         


        
3条回答
  •  爱一瞬间的悲伤
    2020-11-30 03:46

    Since scala 2.10, we can use the reflection of Module:

    import scala.reflect.runtime.universe
    
    val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
    val module = runtimeMirror.staticModule("SomeObject")
    val obj = runtimeMirror.reflectModule(module)
    val someTrait:SomeTrait = obj.instance.asInstanceOf[SomeTrait]  
    someTrait.someMethod
    

提交回复
热议问题