How do I call a Scala Object method using reflection?

前端 未结 3 816
清歌不尽
清歌不尽 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:45

    def companion[T](name : String)(implicit man: Manifest[T]) : T = 
        Class.forName(name + "$").getField("MODULE$").get(man.erasure).asInstanceOf[T]
    
    val result = companion[SomeTrait]("SomeObject").someMethod
    

提交回复
热议问题