用反射获取 case class 注释?

Get case class annotations with reflection?

我有一个案例 class 比如:

case class Foo (@Annotation bar: String)

我希望能够访问该注释及其存储的任何信息

我可以通过

使用 Scala 反射(使用 2.11.8)获得案例访问器
val caseAccessors = 
  universe.typeTag[T].
    tpe.
    decls.
    filter(_.isMethod).
    map(_.asMethod).
    filter(_.isCaseAccessor)

但是当我尝试访问 .annotations 时,什么也没有。我知道注解在技术上是在构造函数参数上,但我如何才能得到它?

您的 @Annotation 将在构造函数参数和伴随对象 apply 方法上,您可以通过名称找到它们。我认为不存在过滤构造函数/主构造函数/伴随对象工厂方法的特定方法。这两个都应该有效:

universe.typeTag[Foo]
  .tpe
  .declarations
  .find(_.name.toString == "<init>")
  .get
  .asMethod
  .paramss
  .flatten
  .flatMap(_.annotations)

universe.typeTag[Foo.type]
  .tpe
  .declarations
  .find(_.name.toString == "apply")
  .get
  .asMethod
  .paramss
  .flatten
  .flatMap(_.annotations)

(虽然我使用的是 Scala 2.11.8 并且没有 decls 但有 declarations

如果你想把注释放在字段或 getter 上,使用 scala.annotation.meta 包:

import scala.annotation.meta
case class Foo (@(Annotation @meta.getter) bar: String)

在这种情况下,您的代码将起作用(如果您在 typeTag[T] 中将 T 更改为 Foo

请参阅 scala.annotation.meta

的文档