jeudi 21 mai 2015

scala how to construct enumeration with string by reflection and type information

This question is about scala reflection.



    object MyEnum extends Enumeration {
        type MyEnum = Value
        val En1, En2 = Value
    }

    case class Data(
        en: MyEnum,
        num: Int
    )

    def initData[T](d: Array[String])(implicit t: ClassTag[T]): T = {
        // using reflection to get type of the parameters
        val clazz = currentMirror.classSymbol(t.runtimeClass)
        val module = clazz.companion.asModule
        val im = currentMirror.reflect(currentMirror.reflectModule(module).instance)
        val ts = im.symbol.typeSignature
        val methodName = "apply"
        val constructor = ts.member(TermName(methodName)).asMethod
        for (ps 

In Java, it is related simple. But It is so hard to link Type and reconstruct it in Scala.





Aucun commentaire:

Enregistrer un commentaire