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

编程入门 行业动态 更新时间:2024-10-26 10:37:31
本文介绍了如何以编程方式确定该类是案例类还是简单类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

解决方案

当前(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.

更多推荐

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

本文发布于:2023-11-03 16:42:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:案例   简单   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!