how can i reflect the instantiated return type of a generic type's method?

Leon <[email protected]> Mon, 7 Mar 2016 01:09:23 -0800 (PST)
Newsgroups gmane.comp.lang.scala
Message-ID <[email protected]>
Hi,

I have just write a method to reflect the methods of case class, but meet 
some problem, the code is:


    case class Name(first: String, last: String)
    case class Person[T](name: T, age: Int)
    case class America(val name: Name, val age: Int)

    val m = runtimeMirror(getClass.getClassLoader)

    def getFlattenFields(tag: Type, prefix: String = ""): Map[String, 
Method] = {
        val cls = m.runtimeClass(tag)
        tag.members.filter(sym =>
            sym.isMethod && sym.asMethod.isGetter && sym.asMethod.isPublic
        ).flatMap { sym =>
            val methodSym = sym.asMethod
            val returnType = methodSym.returnType
*            // When reflect generic types, the returnType will be 
something like 'T' but not the*
*            // instantiated return type, how can i get the real return 
type instead of the generic*
*            // type ?*
            Map[String, Method](prefix + methodSym.name.toString ->
                cls.getDeclaredMethod(methodSym.name.toString)) ++
                (if (returnType.typeSymbol.isClass && 
returnType.typeSymbol.asClass.isCaseClass) {
                    getFlattenFields(returnType, prefix + 
methodSym.name.toString + ".")
                } else {
                    Map.empty[String, Method]
                })
        } toMap
    }

    println(getFlattenFields(typeOf[Person[Name]]))
    println(getFlattenFields(typeOf[America]))


the result of above is:

Map(age -> public int test.Reflect$Person.age(), name -> public 
java.lang.Object test.Reflect$Person.name())
Map(age -> public int test.Reflect$America.age(), name -> public 
test.Reflect$Name test.Reflect$America.name(), name.last -> public 
java.lang.String test.Reflect$Name.last(), name.first -> public 
java.lang.String test.Reflect$Name.first())

the first line of the result is not my expectation, how can i get the 
second line, but using "println(getFlattenFields(typeOf[Person[Name]]))"?


Thanks very much

-- 
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.