首页 > 解决方案 > 有没有办法从用作注释的案例类中可靠地找到 arg 值?

问题描述

我正在使用 Scala 编程语言。我们正在使用注释在类字段上应用一些元数据

例如

注释类

case class Address(city: City, zip: Zip)  extends StaticAnnotation //City and Zip are Enumeration types

使用注解的类

case class Person
(
  @Address(City.LA, Zip.SomeZip)
  Field: String
)

现在,无论参数的顺序如何,我都想将 city(即 LA)和 zip(即 SomeZip)的值作为字符串检索。

我试过的是这个

val fields = typeOf[Person].typeSymbol.info.decls
      .find(d => d.isMethod && d.asMethod.isPrimaryConstructor)
      .get.typeSignature.paramLists.head
    
for(annotation <- field.annotations){
    println(annotation.toString) //returns Address(City.LA, Zip.SomeZip)
}

上面的代码工作并返回字符串,我可以解析和检索所需的值,如上所示。但它仅在参数以真实顺序提供时才有效 -> (City, Zip) 而不是相反。例如

@Address(zip = Zip.SomeZip, city = City.LA) // returns Address(x$4, x$3)

如何为每个 arg 检索正确的值(如果可能,枚举字符串 ->“LA”、“SomeZip”)?

标签: scalareflectionannotationsshapeless

解决方案


推荐阅读