jeudi 13 avril 2017

Get field names from Scala case class with specific annotation

final class ContactInfo extends StaticAnnotation{}

case class Person(val id: String,
              val firstName: String,
              val lastName: String,
              @ContactInfo val phoneNumbers: Seq[String],
              @ContactInfo val email: String)

def getContactInfoFields[T: TypeTag]: Seq[String] = {
???
}

Expected output getContactInfoFields[Person] = ("phoneNumbers", "email")

Riffing off the answer to a similar question on SO I've tried

def getContactInfoFields[T: TypeTag]: Seq[String] = {
  val fields = typeOf[T].members.collect{ case s: TermSymbol => s }.
    filter(s => s.isVal || s.isVar)

  fields.filter(_.annotations.exists(_.isInstanceOf[ContactInfo]))
    .map(x=>x.name.toString).toSeq
}

However in practice this is returning an empty sequence. What am I missing?





Aucun commentaire:

Enregistrer un commentaire