say, I have the following:
trait SomeTrait { def someMethod: String; } object SomeObject extends SomeTrait { def someMethod = "something"; }
I would like to call "someMethod" using reflection as I have the object name as a String. Something like:
val objectName = "SomeObject" val someTrait:SomeTrait = ???.asInstanceOf[SomeTrait] someTrait.someMethod
or something similar.
Thanks
Types obtained through reflection can be instantiated by invoking their constructor using an appropriate “invoker” mirror (mirrors are expanded upon below). Let's walk through an example using the REPL: scala> case class Person(name: String) defined class Person scala> val m = ru. runtimeMirror(getClass.
A classOf[T] is a value of type Class[T] . In other words, classOf[T]: Class[T] . For example: scala> val strClass = classOf[String] strClass: Class[String] = class java. lang. String scala> :t strClass Class[String]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With