-1

So the question is, is it possible to import Scala object object in runtime as a usual scala class e.g.:

trait A
class B extends A
Class.forName("B").newInstance().asInstanceOf[A]

But in case if class B becomes object B it won't work. Are there any other options for Scala Object?

dkim
  • 3,930
  • 1
  • 33
  • 37
tcafrin22
  • 59
  • 1
  • 10
  • Why would you want to do so? – cchantep Nov 15 '17 at 17:05
  • What do you even mean by "But in case if class B becomes object B it won't work."? – sarveshseri Nov 15 '17 at 17:25
  • "it won't work" is not a precise enough error description for us to help you. *What* doesn't work? *How* doesn't it work? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? – Jörg W Mittag Nov 16 '17 at 06:37

1 Answers1

-2

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]
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66