vendredi 2 décembre 2016

Get generic value class parameter type via reflection

I want to get real Type of generic value class parameter. I tried:

import scala.reflect.runtime.universe._

case class Test[T](value: T) extends AnyVal

object Main extends App {
  val tag = implicitly[TypeTag[Test[String]]]
  val constructor = tag.tpe.members.collect {
    case m: MethodSymbol if m.isPrimaryConstructor => m
  }.headOption
  val constructorParams = constructor.map(_.paramLists.flatten).collect {
    case param :: Nil => param
  }
  constructorParams.map(_.typeSignature).foreach(println)
}

but it prints:

T

I know that I can get type arguments with:

tag.tpe.typeArgs.foreach(println)

which outputs:

String

but Test class can be defined like that:

case class Test[T](value: List[T]) extends AnyVal

so type of type argument and parameter type are different.

How can I do this?





Aucun commentaire:

Enregistrer un commentaire