mercredi 15 août 2018

Scala : Error when using reflection to load class and methods

I have a class

class LrGen extends IModelGen {

  var header = Array(
    "First name",
    "last name",
    "address",
    "city",
    "state",
    "zip"
  )

  override def getHeader(separator:String): String =
  {
    header.mkString(separator)
  }

}

I am trying to invoke the getHeader method of that class using reflection following How to invoke method on companion object via reflection? but modified slightly as my class name will vary as well. My code looks like:

val clazzToInvoke = classInitialName+ "Gen"+"$"
import scala.reflect.runtime.universe._

// get runtime universe
val ru = scala.reflect.runtime.universe

// get runtime mirror
val rm = ru.runtimeMirror(this.getClass.getClassLoader)

// get instance mirror for companion object for the class
val moduleSymbol  = rm.reflect(Class.forName(clazzToInvoke))


val methodGetHeader = ru.typeOf[clazzToInvoke.type].decl(ru.TermName("getHeader")).asMethod

println(methodGetHeader("\t"))

However, I am getting error:

error: ru.MethodSymbol does not take parameters
[ERROR]     println(methodGetHeader("\t")

Any insight? Thanks in advance.

For reference My interface looks like :

trait  IModelGen
{
  def getHeader(separator:String): String
}





Aucun commentaire:

Enregistrer un commentaire