给定案例类,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)
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但是我如何以更通用的方式实现它,以便可以方便地将这种技术用于任意类,例如
val fields: List[String] = fieldNames[AnyCaseClass]
Run Code Online (Sandbox Code Playgroud)
是否有图书馆已经为我做到了?
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
721 次 |
| 最近记录: |