mardi 21 avril 2020

Scala Reflection to generate a companion object and call the apply method

Here is the problem.

trait TestTrait[T, R] extends (T => R) 

// Class implementing TestTrait. This is one class, there are a number of class implementing TestTrait
class TestClass(val input: Map[String, String])extends ConfigurableDomainExtractor[String, String] {
  override def apply(value: String): String = ???
}

// Companion Object
object TestClass {
 def apply(properties: Map[String, String]): TestClass = TestClass(properties)
}

what I want to do is to define a method in util class lets say

class CreateInstance {
  def getInstance(fullyQualifiedClassName: String, properties: Map[String, String]): TestTrait = ???

// fullyQualifiedClassName is the name of the class that needs to be instantiated using its companion object. It can be TestClass or any class implementing TestTrait
// properties is the map that needs to be pass to the apply method of the companion object.


}

which will when pass class name , will generate an object of the same class by first getting a companion object and then call apply on the companion object passing the map to generate the class instance.

I know we have reflections in scala and I tried few things but to no avail. Here are few things I tried.

  import scala.reflect.runtime.universe

def getInstance(fullyQualifiedClassName: String, properties: Map[String, String]): TestTrait = {
val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
    val module        = runtimeMirror.staticModule(fullyQualifiedClassName)
    val obj           = runtimeMirror.reflectModule(module)

      obj.instance
        .asInstanceOf[TestTrait[String, String]]
        .apply(properties)
        .asInstanceOf[TestTrait[String, String]]

}

Can someone help me to complete def getInstance method. ?





Aucun commentaire:

Enregistrer un commentaire