【问题标题】:How to find field annotations for a MethodSymbol?如何查找 MethodSymbol 的字段注释?
【发布时间】:2016-08-24 05:00:51
【问题描述】:

假设已经为一个类型找到了一组方法:

case class X()

object A{
   @someannotation
   val x=X()
}

def toType[T](a:T)(implicit tag: TypeTag[T]): Type = tag.tpe

val typ = toType(A)

// Get the public methods that return an X
val intMethods = typ.members.collect{ case m: ru.MethodSymbol if 
   m.isGetter && m.isPublic && m.returnType <:< typeOf[X]  => m }

如何有效地为 intMethods 的每个元素找到相应的注释?

intMethods.head.annotations

为空,因为 typ.decls 中有两个条目用于 x。一个是找到的方法,另一个是保存注释的非方法字段。我可以通过匹配来搜索:

getAnnotations(intMethods.head.toTerm.name.toString.trim)

def getAnnotations( name: String) ={
  typ.decls.filter{ s=>s.name.toString.trim==name.trim && !s.isMethod}.flatMap(_.annotations)
}

但是所有的 toStringing 和 trimming 都非常慢(需要 trim,因为其中一个 decls 包含尾随空格,而另一个不包含)。有没有更好的方法可以直接从 MethodSymbol 中查找对应的类字段?

【问题讨论】:

    标签: scala reflection


    【解决方案1】:

    您可以使用accessed 方法获取getter 的支持字段:

    intMethods.head.accessed.annotations
    

    来自documentation

    /** Backing field for an accessor method, NoSymbol for all other term symbols. */
    abstract def accessed: Universe.Symbol
    

    【讨论】:

      猜你喜欢
      • 2018-12-23
      • 2018-11-27
      • 2013-08-11
      • 2021-09-06
      • 2017-06-19
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      相关资源
      最近更新 更多