给定一个案例类别A
我可以使用以下代码片段使用 Shapeless 提取其字段名称:
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)
}
这一切都很好,但是我如何以更通用的方式实现它,以便我可以方便地将这种技术用于任意类,例如
val fields: List[String] = fieldNames[AnyCaseClass]
是否有图书馆已经为我做到了这一点?
也许是这样的,稍微修改过的版本这个例子 https://gist.github.com/lunaryorn/4b7becbea955ae909af7426d2e2e166c:
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)