确定案例类的字段是否为案例类

时间:2018-07-25 22:55:09

标签: scala reflection

我正在尝试确定任何给定案例类中的成员字段是否也是案例类。取自this答案,给出一个实例或一个对象,我可以将其传递并确定它是否为案例类:

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
} 

我想也许我可以提取字段,它们的类,并使用反射实例化该成员字段的新实例作为其自己的类。我不是100%如何做到这一点,而且似乎有一种更简单的方法。有吗?

1 个答案:

答案 0 :(得分: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?错误

     

字段:MyThing isCaseClass?是

相关问题