【发布时间】: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