How to call the object method (not class method) u

2019-08-07 12:10发布

问题:

This question already has an answer here:

  • How do I call a Scala Object method using reflection? 3 answers

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()

回答1:

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]