和反射class不同,反射class和java反射一样,object是静态代码块模式的单例,Scala 反射的核心是 scala.reflect.runtime.universe:代码如下:
object:
Scala
object TargetObject{
def test1(name:String):String = {
println("11111111")
"1111"
}
}
反射调用:
反射 Scala object 核心是通过 staticModule 获取 ModuleMirror:
Scala
object MyTest {
def main(args: Array[String]): Unit = {
import scala.reflect.runtime.universe
val classMirror = universe.runtimeMirror(getClass.getClassLoader)
val staticMirror = classMirror.staticModule("xxx.xxx.TargetBejte")
val moduleMirror = classMirror.reflectModule(staticMirror)
val objectMirror = classMirror.reflect(moduleMirror.instance)
val sayHelloSymbol = moduleMirror.symbol.typeSignature.member(universe.TermName("test1")).asMethod
val value = objectMirror.reflectMethod(sayHelloSymbol)("yege")
println(value)
}
}