lundi 7 décembre 2015

Scala : Need to create a newInstance of a class using Reflection that takes paramaters

class Config(sourceName :String, storeClass :Class[_]) {

  def store = storeClass.getConstructor(classOf[Configuration]).newInstance(sourceName)

  def write(k :String, v :String) {
   store.writeTo(k,v)
  }

  def read(k :String): Unit ={
   store.readFrom(k)
  }

  def contains(k :String) :Boolean ={
   store.isContains(k)
  }
}

Here Configuration is a parent-abstract class whom are having some child classes.

So the 2nd parameter in class config, can be any child class Configuration.

And each child class takes a parameter while Initiating ie; sourceName.

storeClass.getConstructor(classOf[Configuration]).newInstance(sourceName)

This code above Return Type : Any , which create issue, since i need it to be of Type Configuration

def store :Configuration  

to be of the Type Configuration, otherwise the read,write and contains won't work !





Aucun commentaire:

Enregistrer un commentaire