如何从字段的字符串名称访问案例类字段值 [英] How To Access access Case class field Value from String name of the field
问题描述
我应该如何从表示字段的给定字符串值中提取案例类的字段的值.
How should I extract the value of a field of a case class from a given String value representing the field.
例如:
case class Person(name: String, age: Int)
val a = Person("test",10)
现在给定一个字符串 name
或 age
我想从变量 a
中提取值.我该怎么做呢?我知道这可以使用反射来完成,但我不确定如何?
Now here given a string name
or age
i want to extract the value from variable a
. How do i do this? I know this can be done using reflection but I am not exactly sure how?
推荐答案
使用 Shapeless 镜头可以实现您的需求.这也会在编译时而不是运行时将字段实际存在于案例类上的约束:
What you're looking for can be achieve using Shapeless lenses. This will also put the constraint that a field actually exists on a case class at compile time rather than run time:
import shapeless._
case class Person(name: String, age: Int)
val nameLens = lens[Person] >> 'name
val p = Person("myName", 25)
nameLens.get(p)
产量:
res0: String = myName
如果你试图提取一个不存在的字段,你会得到一个编译时错误,这是一个更有力的保证:
If you try to extract a non existing field, you get a compile time error, which is a much stronger guarantee:
import shapeless._
case class Person(name: String, age: Int)
val nonExistingLens = lens[Person] >> 'bla
val p = Person("myName", 25)
nonExistingLens.get(p)
编译器喊:
Error:(5, 44) could not find implicit value for parameter mkLens: shapeless.MkFieldLens[Person,Symbol with shapeless.tag.Tagged[String("bla")]]
val nonExistingLens = lens[Person] >> 'bla
这篇关于如何从字段的字符串名称访问案例类字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!