mardi 16 février 2021

Is there a way to find arg values reliably from case class which is used as annotation?

I am working in Scala programming language. We are using annotations to apply some metadata on class fields

e.g.

Annotation class

case class Address(city: City, zip: Zip)  extends StaticAnnotation //City and Zip are Enumeration types

Class that uses annotation

case class Person
(
  @Address(City.LA, Zip.SomeZip)
  Field: String
)

Now I want to retrieve the value of city (which is LA) and zip (which is SomeZip) as a string, regardless of the order of the arguments.

what I have tried is this

val fields = typeOf[Person].typeSymbol.info.decls
      .find(d => d.isMethod && d.asMethod.isPrimaryConstructor)
      .get.typeSignature.paramLists.head
    
for(annotation <- field.annotations){
    println(annotation.toString) //returns Address(City.LA, Zip.SomeZip)
}

the above code works and returns the string, which I can parse and retrieve the desired values as shown above. But it works only when the arguments are provided in true order -> (City, Zip) but not the other way around. e.g.

@Address(zip = Zip.SomeZip, city = City.LA) // returns Address(x$4, x$3)

How can i retrieve the correct values (enum strings if possible -> "LA", "SomeZip") for each arg?





Aucun commentaire:

Enregistrer un commentaire