Incerteza
Incerteza

Reputation: 34884

Creating an object dynamically by its name (string)

I have a trait and an object inherited from this trait:

trait MyTrait {
  def method1(a: Int)
}

object MyObject extends MyTrait {
  def method1(a: Int) = //....
}

Assuming I have only the full name of an object as a string (namespace + its name) and knowing it's inherited from MyTrait, how do I

  1. create it at runtime
  2. call its method method1
  3. return it to a calling code so that other clients can use it?

I read about reflection in Scala, but, oddly enough, almost all I found was about creating a class at runtime.

UPDATE:

I wonder, why doesn't this work:

scala>  object MyObject { def method1(a: Int) = 123456 }
defined module MyObject

scala> val cs = Class.forName("MyObject")
java.lang.ClassNotFoundException: MyObject

due to the error java.lang.ClassNotFoundException: MyObject

Upvotes: 3

Views: 2819

Answers (1)

cmbaxter
cmbaxter

Reputation: 35443

If you want to get an instance of a singleton scala object via reflection, you can try this:

package code

object ReflectTest extends App{

  val clazz = Class.forName("code.MyObject$")
  val myObj = clazz.getField("MODULE$").get(classOf[MyTrait]).asInstanceOf[MyTrait]
  println(myObj.method1(2))
}

trait MyTrait {
  def method1(a: Int):Int
}

object MyObject extends MyTrait {
  def method1(a: Int) = a + 1
}

Now I'm not a big fan of obtaining instances of scala objects via reflection (seems kinds silly given that it's a singleton) but maybe you have a valid use case for this.

Upvotes: 8

Related Questions