vendredi 29 septembre 2017

Refer generic class by name

Consider the case that I want to deserialize a JSON string:

def deserialize[T](json)

I can provided class that I want to apply the function explicitly while writing code like

  class Person(name: String)
  deserialize[Person]("""{ "name": "Jennie" }""")

But, what if I need other class, I have to provide it in my code, compile again. I want my program more flexible, it can take a config file that contains name of which class I want to use. So, when ever require a new class, I just need to write the class definition, build it into another jar file, put it in classpath, then restart the program.

    val config = ConfigLoader.load("config.txt")
    val className = config.getString("class-to-deserialize")
    deserialize[<from className to type>](json)

So, is it possible to do that in scala?





Aucun commentaire:

Enregistrer un commentaire