如何以编程方式确定给定类是案例类还是简单类?
解决方案当前(2011年),您可以使用反射来确定类是否实现了接口 scala.Product :
scala> def isCaseClass(o:AnyRef)= o.getClass.getInterfaces.find(_ == classOf [scala.Product])!=无 isCaseClass:(o:AnyRef)Boolean scala> ; isCaseClass(Some(1)) res3:布尔值= true scala> isCaseClass() res4:布尔值= false这只是一个近似值-您可以进一步检查它是否具有 copy 方法,是否实现了 Serializable ,如果它具有一个伴随对象,适当的 apply 或 unapply 方法-本质上,使用反射检查案例类期望的所有内容。 / p>
下一个版本中的scala反射包应使案例类检测更容易,更准确。
编辑:
您现在可以使用新的Scala反射库进行操作-查看其他答案。
How to programmatically determine if the given class is a case class or a simple class?
解决方案Currently (2011), you can use reflection to find out if the class implements the interface scala.Product:
scala> def isCaseClass(o: AnyRef) = o.getClass.getInterfaces.find(_ == classOf[scala.Product]) != None isCaseClass: (o: AnyRef)Boolean scala> isCaseClass(Some(1)) res3: Boolean = true scala> isCaseClass("") res4: Boolean = falseThis is just an approximation - you could go further and check if it has a copy method, if it implements Serializable, if it has a companion object with an appropriate apply or unapply method - in essence, check for all the things expected from a case class using reflection.
The scala reflection package coming in one of the next releases should make case class detection easier and more precise.
EDIT:
You can now do it using the new Scala Reflection library -- see other answer.
更多推荐
如何以编程方式确定该类是案例类还是简单类?
发布评论