如何使用反射调用Scala Object方法?

时间:2010-06-14 18:28:39

标签: reflection scala object

说,我有以下内容:

trait SomeTrait {
  def someMethod: String;
}

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

我想使用反射调用“someMethod”,因为我将对象名称作为String。 类似的东西:

val objectName = "SomeObject"  
val someTrait:SomeTrait = ???.asInstanceOf[SomeTrait]  
someTrait.someMethod

或类似的东西。

由于

3 个答案:

答案 0 :(得分:19)

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

答案 1 :(得分:14)

从scala 2.10开始,我们可以使用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

答案 2 :(得分:13)

对于类,可以使用标准的java反射classOf方法轻松完成。对于Scala对象,它需要更多工作,但仍可以完成:


trait SomeTrait { def someMethod: String}
object SomeObject extends SomeTrait { def someMethod = "something"}

class SomeClass extends SomeTrait { def someMethod = "something"}

object Main {
 def main(args:Array[String]) = {
    val someClassTrait:SomeTrait = Class.forName("SomeClass").newInstance().asInstanceOf[SomeTrait]
    println("calling someClassTrait: " + someClassTrait.someMethod)
    val objectName = "SomeObject$"
    val cons = Class.forName(objectName).getDeclaredConstructors(); 
    cons(0).setAccessible(true);
    val someObjectTrait:SomeTrait = cons(0).newInstance().asInstanceOf[SomeTrait]
    println("calling someObjectTrait: " + someObjectTrait.someMethod)
  }
}

//prints:
calling someClassTrait: something
calling someObjectTrait: something