0

我正在尝试使用 Scala 反射 api 从案例类构建一整套路径。传递给构造函数的参数之一具有作为类型上限的特征(特征的所有实例都是案例类)。在运行时,我只能将这个参数作为特征的实例而不是作为底层案例类来访问。这是一个例子:

trait UpperBound {
 def value: String
}

case class UpperBoundedImpl(value: String, other: String) extends UpperBound

case class Bounded[Upper <: UpperBound](id: String, upper: Upper) 

def getPaths[T](tt: TypeTag[T]): List[String]

val paths = getPaths(typeTag[Bounded[UpperBoundImpl]]).....

The get paths function keeps track of the current path and recursively calls 
the function getTypeConstuctors which is where the problem lies.

def getTypeConstructors(tpe: Type): List[Symbol] = 
  tpe.decls.collect { case meth: MethodSymbol if meth.isCaseAccessor => meth 
}.toList

在这种情况下,我希望 getPaths 返回:[“id”、“upper.value”、“upper.other”]。我已经设法通过从 upper 获取 isStable 符号来破解它以返回 ["id", "upper.value"] 但这不是很好,因为:a)我缺少字段 b)这个解决方案不会泛化(如果嵌套的上部包含嵌套对象本身,我认为它不会应付)。

问题似乎是 Scala 反射 API 将鞋面视为鞋面,即使它是 Bounded[UpperBoundImpl] 的 typeTag。有谁知道我如何让反射 api 将上限视为其运行时/更具体的类型而不是其上限类型?

4

0 回答 0