1

I'd like to call the object main method using reflection in scala. But it did not works, the following 2 lines of code will through exception that I could not create the object using reflection.

val clazz = Class.forName(job.runnerClass)
val runnerClass = clazz.newInstance()
zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • Got the solution here http://stackoverflow.com/questions/3039822/how-do-i-call-a-scala-object-method-using-reflection?rq=1 – zjffdu Apr 05 '13 at 10:34
  • Feel free to delete your own question if it's a duplicate of another. This saves reviewers work determining if it's a duplicate and closing it. – Nathaniel Ford Jun 11 '13 at 20:21

1 Answers1

2

First you have do use an $ at the end of your class name, because scala objects always end with $. You can then find the object instance in a field called MODULE$

val class = Class.forName(name)
val objectInstance = class.getField("MODULE$").get(class).asInstanceOf[YOURCLASSTYPE]
Gevatter Tod
  • 131
  • 4