If B
is an object the following code works:
trait A
object B extends A
val `class` = Class.forName("B$")
val constructor = `class`.getDeclaredConstructors.apply(0)
constructor.setAccessible(true)
constructor.newInstance().asInstanceOf[A]
But this is literal translation of your code from class to object. Creating new instance of B$
violates the contract that there is the only instance of an object in Scala (although some frameworks, especially Java frameworks, can break it too). So it's better to refer the instance cached in MODULE$
`class`.getField("MODULE$")
.get(null) // the field is static, so there's no need in instance
.asInstanceOf[A]