确定一个 case class 的字段是否是另一个 case class。

3

我正在尝试确定在任何给定的案例类中,成员字段是否也是一个案例类。从这个答案中得知,给定一个实例或对象,我可以传递它并确定它是否为案例类:

def isCaseClass(v: Any): Boolean = {
  import reflect.runtime.universe._
  val typeMirror = runtimeMirror(v.getClass.getClassLoader)
  val instanceMirror = typeMirror.reflect(v)
  val symbol = instanceMirror.symbol
  symbol.isCaseClass
}

然而,我想要的是取一个case类,提取其中所有成员字段,并找出哪些是case类本身。可以这样实现:

 def innerCaseClasses[A](parentCaseClass:A): List[Class[_]] = {
  val nestedCaseClasses = ListBuffer[Class[_]]()
  val fields = parentCaseClass.getClass.getDeclaredFields
  fields.foreach(field =>  {
    if (??? /*field is case class */ ) {
      nestedCaseClasses += field.getType
    }
  })
  nestedCaseClasses.toList
} 

我想也许可以提取字段及其类别,并使用反射机制将该成员字段的新实例化作为其自己的类。不过,我并不完全知道如何做到这一点,而且似乎可能有更简单的方法。有吗?

1个回答

2
啊!我已经想通了(简化了确定的功能):
import reflect.runtime.universe._


case class MyThing(str:String, num:Int)
case class WithMyThing(name:String, aThing:MyThing)

val childThing = MyThing("Neat" , 293923)
val parentCaseClass = WithMyThing("Nate", childThing)

def isCaseClass(v: Any): Boolean = {
  val typeMirror = runtimeMirror(v.getClass.getClassLoader)
  val instanceMirror = typeMirror.reflect(v)
  val symbol = instanceMirror.symbol
  symbol.isCaseClass
}

def innerCaseClasses[A](parentCaseClass:A): Unit = {
  val fields = parentCaseClass.asInstanceOf[Product].productIterator
  fields.foreach(field =>  {
    println(s"Field: ${field.getClass.getSimpleName} isCaseClass? " + isCaseClass(field))
  })
} 

innerCaseClasses(parentCaseClass)

打印输出:

字段: 字符串 isCaseClass? false

字段: MyThing isCaseClass? true


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接