2016-12-16 39 views
1

我有一个案例类,如:使用反射获取案例类注释?

case class Foo (@Annotation bar: String) 

我希望能够获得访问该注释和它的任何信息存储

我可以得到的情况下访问器使用反射阶(使用2.11.8)与

val caseAccessors = 
    universe.typeTag[T]. 
    tpe. 
    decls. 
    filter(_.isMethod). 
    map(_.asMethod). 
    filter(_.isCaseAccessor) 

但是当我尝试和他们访问.annotations没有什么。我意识到注释技术上是在构造函数参数上,但我该如何解决?

+0

您的注释是否扩展'scala.annotation.StaticAnnotation'? –

+0

不,这些是另一个库中的java注释,它们对它们具有运行时保留 – devshorts

回答

2

您的@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) 

(虽然我在斯卡拉2.11.8,而且也没有decls但有declarations

如果你想要把你的注解字段或干将,使用scala.annotation.meta包:

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

在这种情况下,你的代码就可以了(如果你在typeTag[T]改变TFoo

请参阅文档scala.annotation.meta

+0

不错,唯一对我有用的东西......但是我怎样才能将它与case类的成员值连接? – bashan