Tom
Tom

Reputation: 245

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 !

Upvotes: 1

Views: 1138

Answers (2)

Jasper-M
Jasper-M

Reputation: 15086

The getConstructor method selects a constructor that accepts parameters of the classes that you provide it. From your code it would appear that you want a constructor that accepts a String, so you probably want to do the following:

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

But I'm not sure if that is the ideal solution to the problem you're trying to solve. Runtime reflection and Class[_] objects are not very Scala-esque...

Upvotes: 2

sjrd
sjrd

Reputation: 22095

Cast it with .asInstanceOf[Configuration]. When using reflection, you have to expect to break type safety.

Upvotes: 2

Related Questions