I have a singleton object implementing a trait in Scala 2.13:
package invalid.so
trait MyTrait {
def myValue: String
}
object MyObject extends MyTrait {
override final val myValue = "my-value"
}
I want to use runtime reflection to get the instance of MyObjectas an instance of MyTrait, based on the fully qualified name "invalid.so.MyObject".
I know how to do this using Java reflection:
val clazz = Class.forName("invalid.so.MyObject$")
val instance: MyTrait = clazz.getField("MODULE$").get(null).asInstanceOf[MyTrait]
However, this is somewhat arcane and requires specific knowledge of the generated JVM values used. In particular, the fact that the class name is "invalid.so.MyObject$" (with a trailing dollar sign) and that the instance is exposed as a static field named "MODULE$", are both nonobvious implementation specifics.
I see that Scala implemented its own reflection capabilities in Scala 2.10 (Reflection Overview), and I wonder if this could be more cleanly used to achieve this goal. Or perhaps there’s another mechanism in Scala to do this.
How can I get the instance of a Scala object by its fully qualified name as an instance of a trait without needing to know the implementation specifics of the JVM class structure?