如何使用 Shapeless 提取字段名称? [英] How to generically extract field names with Shapeless?
本文介绍了如何使用 Shapeless 提取字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个案例类 A
,我可以使用以下代码片段使用 Shapeless 提取其字段名称:
Given a case class A
I can extract its field names with Shapeless using the following snippet:
val fieldNames: List[String] = {
import shapeless._
import shapeless.ops.record.Keys
val gen = LabelledGeneric[A]
val keys = Keys[gen.Repr].apply
keys.toList.map(_.name)
}
这一切都很好,但是我如何以更通用的方式实现它,以便我可以方便地将此技术用于任意类,例如
This works all nice, but how can I implement this in a more generic manner, so that I can conveniently use this technique for arbitrary classes, like
val fields: List[String] = fieldNames[AnyCaseClass]
有没有已经为我做这件事的图书馆?
Is there a library that already does this for me?
推荐答案
可能是这样的,这个例子:
import shapeless._
import shapeless.ops.record._
import shapeless.ops.hlist.ToTraversable
trait FieldNames[T] {
def apply(): List[String]
}
implicit def toNames[T, Repr <: HList, KeysRepr <: HList](
implicit gen: LabelledGeneric.Aux[T, Repr],
keys: Keys.Aux[Repr, KeysRepr],
traversable: ToTraversable.Aux[KeysRepr, List, Symbol]
): FieldNames[T] = new FieldNames[T] {
def apply() = keys().toList.map(_.name)
}
def fieldNames[T](implicit h : FieldNames[T]) = h()
这篇关于如何使用 Shapeless 提取字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文