2

I have two questions. First off, this is my reflection code for instantiating a class constructor via reflection:

 case class RowToScalaConverter[T: TypeTag]() {

    private val tpe: _root_.scala.reflect.runtime.universe.Type = typeOf[T]
    private val symbol: _root_.scala.reflect.runtime.universe.ClassSymbol = tpe.typeSymbol.asClass

    private val classLoaderMirror = runtimeMirror(getClass.getClassLoader)

    private val classMirror: _root_.scala.reflect.runtime.universe.ClassMirror = classLoaderMirror.reflectClass(symbol)

    private val constructorSymbol: _root_.scala.reflect.runtime.universe.Symbol = tpe.decl(termNames.CONSTRUCTOR)

    private val constructorMethod: _root_.scala.reflect.runtime.universe.MethodMirror = classMirror.reflectConstructor(constructorSymbol.asMethod)

    private def build(args: Seq[_]): T = constructorMethod(args: _ *).asInstanceOf[T]

    def rowToClass(row: Row): T = {

      val args = getRowArgs(row)
      print(args)

      build(args)
    }

  }

(Ps, I'm quite aware this is not type safe and that's ok with me, but it's the best I can do for what I want)

First question: Is there a cleaner way to do this? It seems like a lot of boilerplate. I'm not too worried about thread safety, As I plan to define a fixed number of these converters for a certain class [T] at runtime. It just looks kind of ugly.

Second: Would this cause any sort of memory leaks in regards to case class instantiation?

jmc
  • 51
  • 1
  • 6

0 Answers0