我在嵌套列表和 Scala 反射方面遇到了一些麻烦。
如何自省类型的案例类字段List[List[something]]
?
这里有一些代码。它被剥离了——在现实生活中,它构建了关于反射类的静态数据。有趣的部分是inspectField
。
import reflect.runtime.currentMirror
import reflect.runtime.universe._
case class Pet(val name: String, val legs: Int)
case class ListList2(val name: String, val stuff: List[List[Pet]])
object Boom extends App {
// Introspect class and find all its members (constructor fields)
val symbol = currentMirror.classSymbol(Class.forName("com.br.ListList2"))
val constructor = symbol.toType.members.collectFirst {
case method: MethodSymbol if method.isPrimaryConstructor && method.isPublic && !method.paramss.isEmpty && !method.paramss.head.isEmpty => method
}.getOrElse( throw new IllegalArgumentException("Case class must have at least 1 public constructor having more than 1 parameters."))
// Loop through each field
constructor.paramss.head.map( c => inspectField(c) )
private def inspectField[T]( sym:Symbol ) : String = {
val cname = sym.name.toString
println("Field: "+cname)
val cType = sym.typeSignature
if( cType.typeSymbol.fullName.toString == "scala.collection.immutable.List" ) {
println("C: "+cType)
val subtype = cType.asInstanceOf[TypeRef].args(0) // Goes boom here on first recursive call
println("Sub:"+subtype)
inspectField(subtype.typeSymbol)
}
"Hi"
}
}
我的案例类指定了一个类型的字段List[List[Animal]]
。我希望我的inspectField
代码被递归调用。第一次通过没有问题。它打印:
Field: name
Field: stuff
C: scala.List[scala.List[com.br.Pet]]
Sub:scala.List[com.br.Pet]
到目前为止,这就是我所期望的。现在在递归调用到inspectField
这个时候传递subtype
第一个调用(List[Pet])
。我期望这样的输出:
Field: stuff
C: scala.List[com.br.Pet]
Sub:com.br.Pet
取而代之的是,这会随着一个错误而蓬勃发展:
Exception in thread "main" java.lang.ClassCastException: scala.reflect.internal.Types$PolyType cannot be cast to scala.reflect.api.Types$TypeRefApi