Scala 确定案例类的字段是否为案例类
我试图弄清楚任何给定的case类中的成员字段是否也是case类。根据答案,给定一个实例或一个对象,我可以传递它并确定它是否是一个case类:Scala 确定案例类的字段是否为案例类,scala,reflection,Scala,Reflection,我试图弄清楚任何给定的case类中的成员字段是否也是case类。根据答案,给定一个实例或一个对象,我可以传递它并确定它是否是一个case类: def isCaseClass(v: Any): Boolean = { import reflect.runtime.universe._ val typeMirror = runtimeMirror(v.getClass.getClassLoader) val instanceMirror = typeMirror.reflect(v)
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
}
我想也许我可以提取字段及其类,并使用反射将该成员字段的新实例实例化为它自己的类。我不是百分之百地知道如何做到这一点,似乎有一个更简单的方法。有吗?啊!我已经算出了(简化了告诉决定的函数):
打印输出:
字段:字符串isCaseClass?假的
字段:虚构isCaseClass?真的
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)