Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a Scala Object method using reflection?

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

like image 300
sanjib Avatar asked Jun 14 '10 18:06

sanjib


People also ask

How to use reflection in Scala?

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.

What is classOf in Scala?

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]


1 Answers

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 
like image 107
Thomas Jung Avatar answered Sep 21 '22 02:09

Thomas Jung