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

2019-08-07 12:07发布

This question already has an answer here:

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条回答
太酷不给撩
2楼-- · 2019-08-07 12:43

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]
查看更多
登录 后发表回答