mardi 23 août 2016

How to find field annotations for a MethodSymbol

Suppose that have a found a set of methods for a Type:

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 }

How would I efficiently find the corresponding annotations for each element of intMethods?

intMethods.head.annotations

is empty because there are two entries in typ.decls for x. One is the found method and the other is the non-method field that holds the annotations. I can search by matching on:

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)
}

but all that toStringing and trimming is extremely slow (the trim is required because, one of the decls contains a trailing space, and the other not). Is there a better way to directly lookup a corresponding class field from a MethodSymbol?





Aucun commentaire:

Enregistrer un commentaire