scalaimplicitimplicit-parameters

How to instantiate a class by name in Scala which requires an implicit parameter?


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?


Solution

  • 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)