如何以编程方式确定该类是案例类还是简单类? [英] How to programmatically determine if the class is a case class or a simple class?

查看:40
本文介绍了如何以编程方式确定该类是案例类还是简单类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式确定给定类是案例类还是简单类?

解决方案

当前(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 = false

This 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.

这篇关于如何以编程方式确定该类是案例类还是简单类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆