我正在寻找获得案例类定义。
从SO中,我按照Get field names list from case class收集了这个实践,答案是Dia Kharrat使用反射。
一些实验中,我有一个案例类引用另一个案例类,嵌套。我们可以得到元数据很容易地扩展在某种方式?
import scala.collection.mutable.ArrayBuffer
case class MyChgClass(b: Option[String], c: Option[String], d: Option[String])
case class MyFullClass(k: Int, b: String, c: String, d: String)
case class MyEndClass(id: Int, after: MyFullClass)
def classAccessors[T: TypeTag]: List[MethodSymbol] = typeOf[T].members.collect {
case m: MethodSymbol if m.isCaseAccessor => m
}.toList
val z1 = classAccessors[MyChgClass]
val z2 = classAccessors[MyFullClass]
val z3 = classAccessors[MyEndClass]
退货:
z1: List[reflect.runtime.universe.MethodSymbol] = List(value d, value c, value b)
z2: List[reflect.runtime.universe.MethodSymbol] = List(value d, value c, value b, value k)
z3: List[reflect.runtime.universe.MethodSymbol] = List(value after, value id)
因此:
1.正在查找扩展事例类MyEndClass。
1.选项方面似乎未提供。可能吗?
1条答案
按热度按时间1cklez4t1#
1.选项方面似乎未提供。可能吗?
您是否正在寻找
.name
和.typeSignature
?如果您的类在编译时已知,则使用编译时反射(即macros而不是runtime reflection)是有意义的
x一个一个一个一个x一个一个二个x
更好的方法是使用一个将这些宏封装到类型类中的库,在Shapeless中,访问case-class字段的名称和类型的类型类是
LabelledGeneric
一个三个三个一个
1.希望扩展案例类
MyEndClass
。您可以尝试类型类
LabelledGeneric
、Mapper
等的深度版本。Deriving nested shapeless lenses using only a type
Weird behavior trying to convert case classes to heterogeneous lists recursively with Shapeless
https://github.com/milessabin/shapeless/blob/main/examples/src/main/scala/shapeless/examples/deephlister.scala
Converting nested case classes to nested Maps using Shapeless
Automatically convert a case class to an extensible record in shapeless?