mercredi 19 avril 2017

Get all annotations of another class inside scala macro annotation

I'm trying to write an annotation for case classes to dynamically add methods for getting MongoDB Document instance. Everything works fine, except the situation of nested case classes:

@MongoEntity
final case class Person(name: String, info: DetailedInfo)

@MongoEntity
final case class DetailedInfo(info: String)

The reason of that is annotations method always return empty collection. In the snippet below accessors method return types using c.typecheck function.

def generateMethods(classType: TypeName, fields: List[ValDef]) = {
  val typedFields = accessors(fields)

  q"""
    ${Modifiers(Flag.IMPLICIT)} def toDoc(model: $classType): org.mongodb.scala.Document = {
      org.mongodb.scala.Document(
        ..${typedFields.map {
          // annotations is always empty =(
          case accessor if accessor.symbol.asType.annotations.exists(_.eq(MongoEntity)) => q"""${accessor.name.toString} -> ${accessor.name}.toDoc(model.${accessor.name})"""
          case accessor if accessor.paramType <:< typeOf[TraversableLike[_, _]] => q"""${accessor.name.toString} -> model.${accessor.name}.toList"""
          case accessor => q"""${accessor.name.toString} -> model.${accessor.name}"""
        }}
      )
    }
   """
}

How can I get the list of annotations of another case class ?





Aucun commentaire:

Enregistrer un commentaire