0

I have a class declared like this:

class XYZ(implicit sys: ActorSystem) extends Enricher {

}

In a function, I am instantiating the class using the name of the class(here: className).

I tried to do it like this:

 val clazz = Class.forName(className, true, getClass.getClassLoader) 

asSubclass classOf[Enricher]

 clazz.newInstance()

But this only works if the constructor does not require any argument.

How do I go about this?

white-hawk-73
  • 856
  • 2
  • 10
  • 24

1 Answers1

2

You can pass the argument explicitly if you grab the right constructor. If you know that there is only one constructor, you could just do:

 clazz.getConstructors.head.newInstance(sys)

If there can be several, you'll have to iterate through them, looking for the one, whose number of arguments, and their types match what you have.

 clazz
   .getConstructors
   .filter { _.getParameterTypes.size == 1 }
   .find { 
     _.getParameterTypes.head.isAssignableFrom(classOf[ActorSystem])
   }.newInstance(sys)
Dima
  • 39,570
  • 6
  • 44
  • 70