mardi 7 mars 2017

Scala reflect string to singleton object

I'm looking for a way to convert a Scala singleton object given as a string (for example: package1.Main) to the actual instance of Main, so that I can invoke methods on it.

Example of the problem:

package x {
  object Main extends App {
    val objectPath: String = io.StdIn.readLine("Give an object: ") // user enters: x.B

    // how to convert the objectPath (String) to a variable that references singleton B?
    val b1: A = magicallyConvert1(objectPath)
    b1.hi()

    val b2: B.type = magicallyConvert2(objectPath)
    b2.extra()
  }

  trait A {
    def hi() = {}
  }

  object B extends A {
    def extra() = {}
  }
}

How can the magicallyConvert1 and magicallyConvert2 functions be implemented?





Aucun commentaire:

Enregistrer un commentaire