如何轻松获取 Scala 案例类的名称?
给定:
case class FirstCC {
def name: String = ... // something that will give "FirstCC"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
如何从 one.name
获取 "FirstCC"
和从 two.name
获取 "SecondCC"
?
Given:
case class FirstCC {
def name: String = ... // something that will give "FirstCC"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
How can I get "FirstCC"
from one.name
and "SecondCC"
from two.name
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
或者,如果您只想要不带包的名称:
请参阅 java.lang.Class 了解更多信息。
Or if you want only the name without the package:
See the documentation of java.lang.Class for more information.
您可以使用案例类的属性
productPrefix
:NB
如果你传递到 scala 2.8 扩展一个已被弃用的案例类,你必须不要忘记左右父
()
You can use the property
productPrefix
of the case class:N.B.
If you pass to scala 2.8 extending a case class have been deprecated, and you have to not forget the left and right parent
()
下面是一个 Scala 函数,它可以从任何类型生成人类可读的字符串,并在类型参数上递归:
https:// gist.github.com/erikerlandson/78d8c33419055b98d701
Here is a Scala function that generates a human-readable string from any type, recursing on type parameters:
https://gist.github.com/erikerlandson/78d8c33419055b98d701
这将删除某些类末尾出现的
$1
。This will remove the
$1
appearing at the end on some classes.